My Accpeted Java Solution


  • 0
    J

    Hi everyone this is my accepted Java solution. Since the list is sorted, so I did two while loops. Let me know if you have any suggestion :)

    public ListNode deleteDuplicates(ListNode head) {
        ListNode temp = head;
        while (temp != null) {
            while(temp.next != null && temp.next.val == temp.val) {
               temp.next = temp.next.next;
            }
            temp = temp.next;
        }
        return head;
    }

  • 0
    Y

    This is my accepted Java solution. I use one while loop, but do the same things with you. :)

    public ListNode deleteDuplicates(ListNode head) {
    	if (head == null)
    		return null;
    
    	ListNode node = head;
    	ListNode nextNode = null;
    
    	while (node != null) {
    
    		nextNode = node.next;
    		
    		if (nextNode == null) {
    			node.next = nextNode;
    			node = node.next;
    		} else if (node.val == nextNode.val) {
    			node.next = nextNode.next;
    		} else {
    			node = node.next;
    		}
    	}
    
    	return head;
    }

  • 0
    G

    you can delete the first line since you are asking it in the while condition


Log in to reply
 

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