forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-linked-list-elements.cpp
46 lines (43 loc) · 1.01 KB
/
remove-linked-list-elements.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
// Time: O(n)
// Space: O(1)
/**
* 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) {
ListNode dummy{0};
dummy.next = head;
auto *prev = &dummy, *cur = dummy.next;
while (cur) {
if (cur->val == val) {
prev->next = cur->next;
delete cur;
} else {
prev = cur;
}
cur = cur->next;
}
return dummy.next;
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
ListNode* removeElements(ListNode* head, int val) {
for (auto *indirect = &head; *indirect != nullptr; ) {
if ((*indirect)->val == val) {
*indirect = (*indirect)->next;
continue;
}
indirect = &((*indirect)->next) ;
}
return head;
}
};