Skip to content

Commit d4e96b8

Browse files
committed
Create remove-linked-list-elements.cpp
1 parent c29c4e4 commit d4e96b8

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/remove-linked-list-elements.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode(int x) : val(x), next(NULL) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
ListNode* removeElements(ListNode* head, int val) {
15+
auto dummy = ListNode(0);
16+
dummy.next = head;
17+
auto *prev = &dummy, *cur = dummy.next;
18+
19+
while (cur) {
20+
if (cur->val == val) {
21+
prev->next = cur->next;
22+
delete cur;
23+
} else {
24+
prev = cur;
25+
}
26+
cur = cur->next;
27+
}
28+
return dummy.next;
29+
}
30+
};

0 commit comments

Comments
 (0)