Simple iterative Java solution


  • 0
    W
    class Solution
    {
        public ListNode removeElements(ListNode head, int val)
        { 
            /* Skip over invalid nodes at head */
            while (head != null && head.val == val)
                head = head.next;
            
            /* empty list */
            if (head == null)
                return head;
           
            /* fast/slow runner pointers */
            ListNode i = head;  
            for (ListNode j = head.next; j != null; j = j.next) {
                if (j.val != val) {
                    i.next = j;
                    i = i.next;
                }
                
                if (j.next == null) {
                    i.next = null;
                }
            }
            return head;
        }
    }
    

Log in to reply
 

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