Lintcode – Remove Duplicates from Sorted List II

Lintcode – Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct numbers from the original list.

c++:

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution{
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode * deleteDuplicates(ListNode *head) {
        // write your code here
        if (head==NULL) return NULL;
        if (head->next==NULL) return head;
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        ListNode *currNode = dummy;
        while (currNode->next!=NULL && currNode->next->next!=NULL) {
            if (currNode->next->val == currNode->next->next->val) {
                int tmpVal = currNode->next->val;
                while (currNode->next!=NULL && currNode->next->val == tmpVal) {
                    currNode->next = currNode->next->next;
                }
            } else {
                currNode = currNode->next;
            }
        }
        
        return dummy->next;
    }
};

Leave a Reply

Your email address will not be published.