Java: iterative solution, using a dummy head


  • 1
    E
        public ListNode removeElements(ListNode head, int val) {
            if (head == null) return head;
            // Create a dummy node and make it a new head
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            // Initialize a runner, that is going to scan through the list
            ListNode runner = dummy;
            while (runner.next != null) {
                // Found a duplicate - remove it
                if (runner.next.val == val) {
                    runner.next = runner.next.next;
                } else {
                    // Otherwise advance the runner one step further
                    runner = runner.next;
                }
            }
            // Return the real head
            return dummy.next;
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.