-
Notifications
You must be signed in to change notification settings - Fork 0
/
203-RemoveLinkedListElements.cpp
47 lines (44 loc) · 1.18 KB
/
203-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
43
44
45
46
47
/*=============================================================================
# FileName: 203-RemoveLinkedListElements.cpp
# Desc:
# Author: qsword
# Email: huangjian1993@gmail.com
# HomePage:
# Created: 2015-05-12 21:26:38
# Version: 0.0.1
# LastChange: 2015-05-12 21:26:38
# History:
# 0.0.1 | qsword | init
=============================================================================*/
#include <leetcode.h>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
//38ms
ListNode* removeElements(ListNode* head, int val) {
if (!head) {
return head;
}
while (head && head->val == val) {
head = head->next;
}
if (!head || !(head->next)) {
return head;
}
ListNode *tail = head;
while (tail->next) {
while (tail->next && tail->next->val != val) {
tail = tail->next;
}
if (!(tail->next)) {
return head;
}
tail->next = tail->next->next;
}
return head;
}
};