My C++ solution


  • 0
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if (!head || !head->next) return head;
    		ListNode *front = new ListNode(0);
    		front->next = head;
    		head = front;                              //insert head node
    		ListNode *phead = head, *post= phead->next, *prev = post->next;
    		while (prev){
    			if (prev->val == post->val){
    				post->next = prev->next;
    				ListNode *temp = prev;
    				prev = prev->next;
    				delete temp;
    				if ((prev == nullptr) || (prev->val != post->val)){    // notice the order besides || 
    					phead->next = post->next;
    					ListNode* temp = post;
    					delete temp;
    					if (!prev || !prev->next) return front->next;
    					post = prev;
    					prev = prev->next;
    				}
    			}
    			else{
    				phead = phead->next;
    				post  = phead->next;
    				prev  = post->next;
    			}
    		}
    		return front->next;
        }
    };

Log in to reply
 

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