leetcode-Remove Duplicates from Sorted List II

Posted Shirley_ICT

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-Remove Duplicates from Sorted List II相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

分析:

设置三个指针,pre, cur, next, 然后进行模拟删除操作,比较简单,具体代码如下:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL || head->next == NULL)
        {
            return head;
        }
        ListNode dummy(-1);
        dummy.next = head;
        ListNode *pre = &dummy;
        ListNode *cur = head;
        while(cur != NULL && cur->next != NULL)
        {
            ListNode *next = cur->next;
            if(cur->val != next->val)
            {
                pre = cur;
                cur = cur->next;
            }
            else
            {
                while(next != NULL && cur->val == next->val)
                {
                    cur = cur->next;
                    next = cur->next;
                }
                pre->next = next;
                cur = next;
            }
        }
        return dummy.next;
    }
};

 

以上是关于leetcode-Remove Duplicates from Sorted List II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Remove Invalid Parentheses

LeetCode-Remove Linked List Elements

leetcode-Remove Duplicates from Sorted Array

LeetCode-Remove Duplicates from Sorted Array II

leetcode-Remove Duplicates from Sorted Array II-80

Contains Duplicate,Contains Duplicate II,Contains Duplicate III