203. Remove Linked List Elements
class Solution {
public ListNode removeElements(ListNode head, int val) {
// because we will move head, must have a dummy to return head
ListNode dummy = new ListNode(0);
dummy.next = head;
// because we will connect the element removed's before and after elements, we must do the operation on the element before it
head = dummy;
while(head.next != null) {
if (head.next.val == val) {
head.next = head.next.next; // skip the element at head.next
} else {
head = head.next;
}
}
return dummy.next;
}
}Last updated