C++ iterative. easy to understand


  • 0
    N
    class Solution {
        // Check if the head has a dup
    	bool hasDup(ListNode *head)
    	{
    		if (head == NULL || head->next == NULL) return false;
    		if (head->val == head->next->val) return true;
    		return false;
    	}
    
        // remove dups and return the next node
    	ListNode *getNext(ListNode *head)
    	{
    		int val = head->val;
    		while (head != NULL && head->val == val) head = head->next;
    		return head;
    	}
    
    public:
    	ListNode* deleteDuplicates(ListNode* head) {
    		if (head == NULL) return NULL;
    		ListNode *cur = head, *prev = NULL;
    
    		while (cur != NULL)
    		{
                        // check dups and get the next node
    			while (hasDup(cur)) cur = getNext(cur);
    
    			if (prev == NULL) // for the first node
    			{
    				head = cur;
    				prev = cur;
    			}
    			else                     // else
    			{
    				prev->next = cur;
    				prev = cur;
    			}
    			if (cur != NULL) cur = cur->next;
    		}
    
    		return head;
    	}
    };

Log in to reply
 

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