题目:
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
题解:
C++版:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head == NULL)
return NULL;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* p = dummy;
while(p && p->next) {
if(p->next->val == val) {
p->next = p->next->next;
continue;
}
p = p->next;
}
return dummy->next;
}
};
Java版:
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null)
return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
while(p != null && p.next !=null) {
if(p.next.val == val) {
p.next = p.next.next;
continue;
}
p = p.next;
}
return dummy.next;
}
}
Python版:
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head == None:
return None
dummy = ListNode(0)
dummy.next = head
p = dummy
while p != None and p.next != None:
if p.next.val == val:
p.next = p.next.next
continue
p = p.next
return dummy.next