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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val)
{
if(head == NULL)
return NULL;
ListNode *first = new ListNode(0);
first->next = head;
ListNode *p = head;
ListNode *pre = first;
while(p)
{
if(p->val == val)
{
pre->next = p->next;
}
else
{
pre = p;
}
p = p->next;
}
return first->next;
}
};
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head == None:
return None
first = ListNode(0)
first.next = head
p = head
pre = first
while p:
if p.val == val:
pre.next = p.next
else:
pre = p
p = p.next
return first.next