Using fakeHead and only one pointer


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

Log in to reply
 

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