LeetCode 82. Remove Duplicates from Sorted List II

来源:互联网 发布:海康威视网络配置设置 编辑:程序博客网 时间:2024/05/28 18:45

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.

这道题是Remove Duplicates from Sorted List的扩展,要把所有重复的结点都删除。解法在基本题的基础上(先删掉重复的结点),对重复的数据做一个标记,把最后剩下的结点删除掉。

class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {        if (!head) {            return head;        }        ListNode **pp = &head;        bool isDuplicate = false;        while ((*pp)->next)        {            if ((*pp)->val == (*pp)->next->val)            {                isDuplicate = true;                ListNode *p = *pp;                *pp = (*pp)->next;                delete p;            }            else if (isDuplicate) {                isDuplicate = false;                ListNode *p = *pp;                *pp = (*pp)->next;                delete p;            }            else {                pp = &((*pp)->next);            }        }        if (isDuplicate)        {            ListNode *p = *pp;            *pp = (*pp)->next;            delete p;        }        return head;    }};
阅读全文
0 0