Concise java iterative solution with dummyHead


  • 0
    Z

    Use a dummy head to keep the control of the real head.
    Use a current pointer to denote the new list we wanted to generate.
    Don't forget to set the cur.next to null after the whole loop to get ride of the trailing target val. [1,2,6,3,4,5,6] 6 as an example.

    public ListNode removeElements(ListNode head, int val) {
            ListNode dummyHead = new ListNode(0);
            ListNode cur = dummyHead;
            
            while(head != null){
                if(head.val != val){
                    cur.next = head;
                    cur = cur.next;
                }
                head = head.next;
            }
            cur.next = null;
            return dummyHead.next;
        }
    

Log in to reply
 

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