Wednesday, April 15, 2015

Remove Duplicates from Sorted List

Problem:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Solution:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode *curr = head, *nextDiff = head;
        if (head == NULL)
            return curr;
       
        nextDiff = nextDiff -> next;
        while (nextDiff != NULL) {
            while (nextDiff != NULL && nextDiff -> val == curr -> val)
                nextDiff = nextDiff -> next;
            curr -> next = nextDiff;
            curr = nextDiff;
            if (nextDiff != NULL)
                nextDiff = nextDiff -> next;
        }
        return head;
       
        // Online Sol: shorter one.
        /*
        if (head==NULL){return NULL;}
        if (head->next==NULL){return head;}
        ListNode* list = head;
        while (head->next!=NULL){
           
            if (head->next->val==head->val){
                head->next=head->next->next;
            }else{
                head = head->next;
            }
        }
        return list;
        */
    }
};

No comments:

Post a Comment