Simple iterative java solution


  • 0
    Y
    public ListNode removeElements(ListNode head, int val) {
        while(head!=null&&head.val==val){
            head=head.next;
        }
        ListNode node = head;
        while(node!=null){
            if(node.next!=null&&node.next.val==val)
                node.next=node.next.next;
            else
                node=node.next;
        }
        return head;
    }

  • 0
    V

    use a voidHead can makes code cleaner :), like using one while loop.
    here is my code

    public ListNode removeElements(ListNode head, int val) {
        ListNode voidHead = new ListNode(-1);
        voidHead.next=head;
        ListNode pointer = voidHead;
        while (pointer.next!=null){
            if (pointer.next.val == val){
                pointer.next = pointer.next.next;
            }else {
                pointer =pointer.next;
            }
        }
        return voidHead.next;
    }

  • 0
    Y

    you are right! thank you for suggestion. :)


Log in to reply
 

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