82. Remove Duplicates from Sorted List II

问题描述:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

 

解题思路:

对每一个节点,我们简要检查它是否是一个存在重复的节点,是的话,将指针指向与它值不同的第一个节点,并将它的前一个指针指向它。

我们用到了两个指针:

  1.pre: 记录前一个指针

  2.p:记录现在的指针

在检查p是否是有重复的节点时,我们用了cur来循环

需要注意的是,若一开始就是重复的节点,我们也需要移动头节点。

将头节点移动到第一个值不为原值的节点并检查这个节点

 

代码:

/**
 * 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)
            return head;
        ListNode* pre = head;
        ListNode* p = head;
        while(p){
            ListNode* cur = p->next;
            while(cur && (cur->val == p->val)){
                cur = cur->next;
            }
            if(cur != p->next){
                if(p->val == head->val){
                    head = cur;
                    pre = cur;
                    p = cur;
                }else{
                    pre->next = cur;
                    p = cur;
                }
            }else{
                pre = p;
                p = cur;
            }
        }
        return head;
    }
};

 

posted @ 2018-06-10 06:03  妖域大都督  阅读(84)  评论(0编辑  收藏  举报