Simple Iterative Solution


  • 0
        public ListNode removeElements(ListNode head, int val) {
    		if(head==null) return head;
    		ListNode p = new ListNode(0);
    		p.next = head;
    		ListNode prev = p;
    		ListNode curr = p.next;
    		while(curr!=null) {
    			while(curr!=null && curr.val==val) curr=curr.next;
    			prev.next = curr;
    			if(curr!=null) {
    				curr = curr.next;
    				prev = prev.next;
    			}
    		}
    		return p.next;
    	}

Log in to reply
 

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