Concise java iterative solution with dummyHead

  • 0

    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 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){
           = head;
                    cur =;
                head =;
   = null;

Log in to reply

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