Java 1ms solution


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

Log in to reply
 

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