Skip to content

Commit 917987a

Browse files
committed
Sync LeetCode submission - Remove Linked List Elements (c)
1 parent 81c4ef6 commit 917987a

File tree

1 file changed

+31
-0
lines changed
  • my-folder/problems/remove_linked_list_elements

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
struct ListNode* removeElements(struct ListNode* head, int val) {
2+
if (!head) {
3+
return 0;
4+
}
5+
6+
// Find first non-val element and set it as the head
7+
while (head->val == val) {
8+
head = head->next;
9+
if (!head) {
10+
return 0;
11+
}
12+
}
13+
14+
struct ListNode* last_valid = head;
15+
16+
while (last_valid) {
17+
if (!last_valid->next) {
18+
return head;
19+
}
20+
if (last_valid->next->val == val) {
21+
last_valid->next = last_valid->next->next;
22+
} else {
23+
last_valid = last_valid->next;
24+
}
25+
}
26+
27+
28+
return head;
29+
30+
31+
}

0 commit comments

Comments
 (0)