leetcode_Remove Linked List Elements
2015-05-15 10:13
351 查看
描述:
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
思路:
直接创建一个头结点即可,从头节点开始,while(p.next!=null) if(p.next.data=val)p.next=p.next.next;
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
return head;
ListNode preNode=new ListNode(0);
preNode.next=head;
ListNode pNode=preNode;
while(pNode.next!=null)
{
if(pNode.next.val==val)
pNode.next=pNode.next.next;
else
pNode=pNode.next;
}
return preNode.next;
}
}
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
思路:
直接创建一个头结点即可,从头节点开始,while(p.next!=null) if(p.next.data=val)p.next=p.next.next;
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
return head;
ListNode preNode=new ListNode(0);
preNode.next=head;
ListNode pNode=preNode;
while(pNode.next!=null)
{
if(pNode.next.val==val)
pNode.next=pNode.next.next;
else
pNode=pNode.next;
}
return preNode.next;
}
}
相关文章推荐
- 【leetcode】Remove Linked List Elements
- LeetCode:Remove Linked List Elements
- LeetCode题解——Remove Linked List Elements
- 203.[LeetCode]Remove Linked List Elements
- Remove Linked List Elements [leetcode]
- [C语言][LeetCode][203]Remove Linked List Elements
- Remove Linked List Elements——LeetCode
- LeetCode OJ Remove Linked List Elements
- LeetCode 之 Remove Linked List Elements — C 实现
- Remove Linked List Elements ---LeetCode
- 【Leetcode】Remove Linked List Elements
- 【leetcode】【单链表】【203】Remove Linked List Elements
- LeetCode(2) -- Remove Linked List Elements
- LeetCode-Remove Linked List Elements-解题报道
- LeetCode - Remove Linked List Elements
- [LeetCode] Remove Linked List Elements
- 《leetCode》:Remove Linked List Elements
- Java for LeetCode 203 Remove Linked List Elements
- [LeetCode] Remove Linked List Elements
- leetcode203-Remove Linked List Elements