Leetcode--Remove Duplicates from Sorted List II

来源:互联网 发布:mastercam编程教程 编辑:程序博客网 时间:2024/06/05 02:33

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.

Hide Tags
 Linked List
Have you met this question in a real interview? 


思路:考察分析的严谨性
先看三个例子:
1)  2  2 =》 NULL
2)  2  2  3  3  =》 NULL
3)  1  2   3  3  4  4  5=》 1 2 5


首先,找到head链表中第一个非重复的节点,返回的就是该节点
然后,删除重复所有重复出现的节点。注意,当返回的节点result和当前节点cur指向同一节点时,若cur指向的节点到最后一个节点的值都一样,则返回NULL;

/** * 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) {        if(head==NULL||head->next==NULL)            return head;        ListNode * pre=NULL;        ListNode * cur=head;        ListNode * post=cur->next;                if(cur->val!=post->val)        {            pre=cur;            cur=post;            post=post->next;        }        else        {            while(post!=NULL&&cur->val==post->val)            {                post=post->next;            }                        if(post!=NULL)            {                pre=cur=post;                post=post->next;            }        }                        ListNode *result=pre;        while(cur!=NULL&&post!=NULL)        {            if(cur->val!=post->val)            {                pre=cur;                cur=post;                post=post->next;            }            else{                while(post!=NULL&&cur->val==post->val)                {                    post=post->next;                }                if(result==cur)                {                    if(post!=NULL)                    {                        result=pre=cur=post;                        post=post->next;                    }                    else                        result=NULL;                }                else                {                    if(post!=NULL)                    {                        cur=post;                        post=post->next;                        pre->next=cur;                    }                    else                        pre->next=NULL;                }                            }        }                return result;    }};


0 0
原创粉丝点击