-
Notifications
You must be signed in to change notification settings - Fork 0
/
203remove.cpp
56 lines (50 loc) · 1.14 KB
/
203remove.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//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
//
//Credits:
/**
* 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 ( NULL == head)
{
return head;
}
ListNode*dummynode = new ListNode(0);
dummynode->next = head;
ListNode*prev = dummynode;
ListNode*cur = head;
ListNode*next = head->next;
while(cur)
{
if ( cur->val == val)
{
prev->next = next;
delete cur;
}
else
{
prev = cur;
}
cur = next;
if ( next )
{
next = next->next;
}
}
ListNode*ret = dummynode->next;
delete dummynode;
return ret;
}
};