Java solution easy.


  • 2
    J
     public static ListNode removeElements(ListNode head, int val) {
    		if (head == null) {
    			return null;
    		}
    		while (head != null && head.val == val) {
    			head = head.next;
    		}
    		ListNode node = head;
    		ListNode preNode = head;
    		while (node != null) {
    			if (node.val == val) {
    				preNode.next = node.next;
    				node = node.next;
    			} else if (node.val != val) {
    				preNode = node;
    				node = node.next;
    			}
    		}
    		return head;
    	}

Log in to reply
 

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