My 1ms java solution may help u


  • 1
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode removeElements(ListNode head, int val) {
            while (head != null && head.val == val)
    			head = head.next;
    		if (head == null)
    			return null;
    		ListNode p = head;
    		while (p.next != null) {
    			if (p.next.val == val) {
    				p.next = p.next.next;
    			} else {
    				p = p.next;
    			}
    		}
    		return head;
        }
    }

  • 0

    My 2ms solution is quite similar to yours but it's 2ms:

    public ListNode removeElements (ListNode head, int val) {
    	ListNode result = head;
    	while (result != null && result.val == val) {
    		result = result.next;
    	}
    	ListNode tmp = result;
    	while (tmp != null && (head = tmp.next) != null) {
    		if (head.val == val) {
    			tmp.next = head.next;
    		} else {
    			tmp = head;
    		}
    	}
    	return result;
    }

Log in to reply
 

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