Leetcode 203. Removed LinkedList elements
Problem Description:
I always have trouble understanding how the dummy/curr pointer updates the head pointer
The below code is the solution for the problem statement
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
public ListNode removeElements(ListNode head, int val) {
ListNode curr = head;
while(curr != null && curr.val == val){
curr = curr.next;
}
while(curr != null && curr.next != null){
if(curr.next.val == val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return head;
}
The below code fails for the case head = [7,7,7,7] , val = 7
Expected answer : [], Answer from the above code : [7,7,7,7]
the test case only gets into the first while loop where curr gets updated with its next pointer. I expected head also to be updated (head gets updated when the second while loop in execueted in other test cases) . Any explanation for this would be helpful
Solution – 1
Your code never updates head
, yet if the first node has the value to delete, then head
will need to change… For the example list you provided, the function should even return null.
The first loop in your code should update head
, not curr
. curr
only starts to play a role in the second loop:
public ListNode removeElements(ListNode head, int val) {
while(head != null && head.val == val){
head = head.next;
}
ListNode curr = head;
while(curr != null && curr.next != null){
if(curr.next.val == val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return head;
}