Naive solution in Java


  • 0
    public ListNode removeElements (ListNode head, int val) {
    	ListNode result = head;
    	// move to the first not-val node
    	while (result != null && result.val == val) {
    		result = result.next;
    	}
    	ListNode tail = result;
    	while (tail != null && (head = tail.next) != null) {
    		if (head.val == val) {
    			tail.next = head.next;  // skip the val node
    		} else {
    			tail = head;
    		}
    	}
    	return result;
    }

Log in to reply
 

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