6ms C++ solution


  • 0
    L

    use the val of current node`s node as a sign, to delete all the duplicates. 6ms time complexity.

    ListNode* deleteDuplicates(ListNode* head) {
           if (!head || !head->next)
    		return head;
    	ListNode dummy(0);
    	ListNode *prev = &dummy;
    	dummy.next = head;
    	int val = head->next->val; // val represent the val of current node`s node
    	while (head)
    	{
            /* if there are duplicates, loop to get to next unique node */
    		if (head->val == val) 
    		{
    			while (head && head->val == val)
    				head = head->next;
    			prev->next = head;
    			if (head && head->next) // "if not" is to consider the last two node
    				val = head->next->val;
    			else
    				break;
    		}
            /* if not, go to next node */
    		else
    		{
    			prev = head;
    			head = head->next;
    			if (head->next)
    				val = head->next->val;
    			else
    				break;
    		}
    	}
    	return dummy.next;
        }
    

Log in to reply
 

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