LeetCode 82. Remove Duplicates from Sorted List II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Allenlzcoder/article/details/80349449

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;
    }
};
阅读更多
想对作者说点什么?

博主推荐

换一批

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