Leetcode 203 : Remove Linked List Elements
Solution to Remove Linked List Elements Problem. The first approach uses a dummy pointer to handle the edge case of removing head node itself.
Approach 1:
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode();
dummy.val = -1;
dummy.next = head;
ListNode cur = head;
ListNode pre = dummy;
while(cur != null) {
if(cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
}
Approach 2:
Approach 2 is more cleaner with less variables. Here is a video explaining the same.
public class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head != null && head.val == val) {
head = head.next;
}
ListNode cur = head;
while(cur != null && cur.next != null) {
if(cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}