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.

 

思路:

1 先处理头结点是否有相同,若有相同,则更好头结点,使得head指向新的头结点,处理完后,要么返回空链表,要返回的新链表有一个结点或第1,2两个节点不相等。

2.基于第一步,若新链表只有1个或者2个节点都直接返回,然后用三个指针分别指向第一,二,三个点,接着按常规去除重复结点即可

代码:

class Solution{
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if(head==NULL||head->next==NULL) return head;//空链表或者只要一个结点

        //遍历处理头结点是否有重复(删除后,又有新的头结点),处理后,前两个结点不会相等
        ListNode* pheadnext=head->next;
        while (pheadnext!=NULL&&pheadnext->val==head->val)
        {
            while(pheadnext!=NULL&&pheadnext->val==head->val){
                pheadnext=pheadnext->next;
            }
            if(pheadnext!=head->next) 
            {
                if(pheadnext==NULL) return NULL;
                head=pheadnext;
                pheadnext=head->next;
            }
            else break;
        }
        
        
        ListNode* pre=head;
        ListNode* p=pre->next;
        if(p==NULL) return head;
        ListNode* q=p->next;
     if(q==NULL) return head;
        while(q!=NULL){
            if(p->val==q->val){//比较2,3个结点
                while(q!=NULL&&p->val==q->val){
                    q=q->next;
                }
                pre->next=q;
                if(q!=NULL){
                   p=q;
                   q=p->next; 
                }
                continue;
            }
            pre=pre->next;
            p=p->next;
            q=q->next;
        }
        return head;
    }
};

 

posted @ 2015-01-22 14:18  雄哼哼  阅读(142)  评论(0编辑  收藏  举报