Remove Linked List Elements — Dummy Head
Advertisement
Problem 215 · Remove Linked List Elements
Difficulty: Easy · Pattern: Dummy Head
Solutions
# Python
def removeElements(head, val):
dummy = ListNode(0, head)
cur = dummy
while cur.next:
if cur.next.val == val: cur.next = cur.next.next
else: cur = cur.next
return dummy.next
// Java
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0, head), cur = dummy;
while (cur.next != null) {
if (cur.next.val == val) cur.next = cur.next.next;
else cur = cur.next;
}
return dummy.next;
}
// C++
ListNode* removeElements(ListNode* head, int val) {
ListNode dummy(0, head), *cur = &dummy;
while (cur->next) {
if (cur->next->val == val) cur->next = cur->next->next;
else cur = cur->next;
}
return dummy.next;
}
Complexity
- Time: O(n)
- Space: O(1)
Advertisement