Java solution 1ms


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

Log in to reply
 

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