Iterative short Java solution

  • 45

    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 =;
            ListNode curr = head;
            while (curr != null && != null)
                if ( == val) =;
                else curr =;
            return head;

  • 0

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

  • 0

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

  • -2

    @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

    @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

    @strmrdr u r right

Log in to reply

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