Iterative short Java solution


  • 48
    S

    Hi guys!

    Here's an iterative solution without dummy head.
    First, we shift a head of a list while its' value equals to val.
    Then, we iterate through the nodes of the list checking if the next node's value equals to val and removing it if needed.


    public class Solution {
        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;
                else curr = curr.next;
            return head;
        }
    }

  • 1
    Z

    Hello, what's the difference between using a dummy head and without a dummy head?


  • 0
    N

    @zack_ZJW "curr" will point to the last node while "head" pointing the first one.


  • -1
    S

    @shpolsky this solution is wrong because does not handle the tail.
    Try 'Input [1,1] ,remove 1' test case, return [1] not expected [].
    Dummy head way is born for that.


  • 0
    S

    @saiisa That is simply incorrect because the first while loop will eliminate all nodes, thus returning null. Did you even bother to test your assertion?


  • 0
    S

    @strmrdr u r right


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

Log in to reply
 

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