Accepted easy Java solution 1ms one-pass


  • 0
    D

    public class Solution {

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

    }


  • 0

    My Java version, time O(n), space O(1)

    public class Solution {
        public ListNode removeElements(ListNode head, int val) {
            
            if(head == null) return head;
            
            while(head.val == val){
                if(head.next != null){
                    head = head.next;
                } else {
                    return null;
                }
            }
            
            ListNode current = head;
            
            while(current.next != null){
                if(current.next.val == val){
                    current.next = current.next.next;
                } else {
                    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.