forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveLinkedListElements.cpp
44 lines (38 loc) · 1.13 KB
/
RemoveLinkedListElements.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
// Source : https://leetcode.com/problems/remove-linked-list-elements/
// Author : Hao Chen
// Date : 2015-06-09
/**********************************************************************************
*
* 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:Special thanks to @mithmatt for adding this problem and creating all test cases.
*
**********************************************************************************/
/**
* 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) {
static ListNode dummy(-1);
dummy.next = head;
ListNode *p = &dummy;
while( p->next) {
if (p->next->val == val) {
p->next = p->next->next;
}else{
p = p->next;
}
}
return dummy.next;
}
};