【Leetcode长征系列】Remove Duplicates from Sorted List II

来源:互联网 发布:留学低龄化数据 编辑:程序博客网 时间:2024/04/30 15:22

原题:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct 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.

代码:

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

需要注意的特殊情况:

1. {1}

2. {1->2}

3. {1->1->2}

要注意pre的初始值!NULL最佳,本次情况下不适合用head作为初始值。

0 0