Allenlzcoder的博客

快来关注我啊!!!

LeetCode 82. Remove Duplicates from Sorted List II

LeetCode 82. Remove Duplicates from Sorted List II

Solution1:我的答案
借鉴LeetCode 86中Solution2的技巧实现的算法,哈哈哈哈,挺好!
增加头结点,会大大方便各种操作!!!

/**
 * 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;
        vector<int> dupli;         //记录下重复数字
        struct ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        struct ListNode *cur = dummy;
        while (cur->next) {
            if (cur->next->next == NULL) {
                if (!dupli.empty() && cur->next->val == dupli.back()) {
                    cur->next = NULL;
                    break;
                }
                else break;
            }
            else {
                if (cur->next->next->val != cur->next->val) {
                    if (!dupli.empty() && cur->next->val == dupli.back())
                        cur->next = cur->next->next;
                    else 
                        cur = cur->next;
                }
                else {
                    dupli.push_back(cur->next->val);
                    cur->next = cur->next->next;
                }
            }
        }
        return dummy->next;
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Allenlzcoder/article/details/80349449
个人分类: LeetCode练习题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode 82. Remove Duplicates from Sorted List II

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭