Friday, August 21, 2015

Remove Linked List Elements | Leetcode

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

---

Solution: First remove all the starting nodes with node.val == val. Update the head pointer accordingly to return later. Iterate through the remaining list while maintaining the previous and current pointers. Whenever we find a matching "curr.val == val", remove it by doing "prev.next = curr.next". Return the head pointer as the answer.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        while (true) {
            if (head == null) return null;
            if (head.val != val) break;
            head = head.next;
        }

        ListNode prev = head;
        ListNode curr = prev.next;
        
        while (curr != null) {
            if (curr.val == val) {
                prev.next = curr.next;
            } else {
                prev = curr;
            }
            curr = curr.next;
        }
        
        return head;
    }
}

No comments: