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.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

思路: 就是一次顺序遍历,然后操作几个指针。这里加了一个fakehead或者dummynode,方便处理。

边界情况!!!这个确实是个问题,发现好多算法出错就是边界。这个要多想想。多训练训练自己。 

这个的时间,leetcode里排名在中间。。。。。郁闷,我要改进下。

/**
 * 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 *pre,*p;
        ListNode *phead=new ListNode(0);
        phead->next=head;
        pre=phead;
        p=pre->next;
        bool duplicatedFlag=false;
        while(p && p->next){
            if(p->val==p->next->val){ 
                duplicatedFlag=true;
                p=p->next;
            }
            
            if(duplicatedFlag){
                duplicatedFlag=false;
                pre->next=p->next;
                if(pre->next)p=pre->next;
            }else{
                pre=pre->next;
                p=pre->next;
            }
        }
        return phead->next;
    }
};

 

posted @ 2015-03-19 23:37  jasmine_turnsoul  阅读(91)  评论(0)    收藏  举报