Easy Java code to understand


  • 0
    J

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

        return dummy.next;
    }
    

    Very easy and clear. The key is that only when head.next.val != val, the head go to head.next.


Log in to reply
 

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