Simple C++ iterative solution (8ms)


  • 0
    J
    ListNode* deleteDuplicates(ListNode* head) {
    	if (!head) return head;
    
    	ListNode* fakeHead = new ListNode(INT_MIN);
    	ListNode* prev = fakeHead;
    	fakeHead->next = head;
    	ListNode* cur = head;
    
    	while (cur) {
    		if (cur->next && cur->val == cur->next->val) {
    			int val = cur->val;
    			while (cur && cur->val == val) {
    				ListNode* t = cur->next;
    				prev->next = t;
    				delete cur;
    				cur = t;
    			}
    		}
    		else {
    			prev = cur;
    			cur = cur->next;
    		}
    	}
    
    	return fakeHead->next;
    }

Log in to reply
 

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