Wednesday, August 12, 2015

Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Have you met this question in a real interview? 
Yes
Example
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Tags Expand  


就是个比较tricky的题目,画一画就是,永远去重复元素之前的为head,那么在循环里需要判断head->next && head->next->next 存在且数值相等,然后移除,否则遍历。 取巧的地方就是知道重复元素永远存在两个以上,所以不需要担心。。。。


/**
 * 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
        ListNode dummy(0);
        dummy.next=head;
        head=&dummy;
        while(head){
            if (head->next && head->next->next && head->next->val ==head->next->next->val){
                int val=head->next->val;
                while(head->next && head->next->val==val){
                    ListNode* tmp=head->next;
                    head->next=tmp->next;
                    delete tmp;
                }
            } else{
                head=head->next;
            }
        }
        return dummy.next;
    }
};

No comments:

Post a Comment