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;
    }
};

 

posted @ 2016-05-24 11:25  Shirley_ICT  阅读(124)  评论(0编辑  收藏  举报