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.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

这道题特别简单,其实关于链表的题都没有什么技巧,就是一堆的指针指来指去.

/**
 * 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) {
       ListNode *pre,*now,*Head;
        if(!head||!head->next)return head;
        Head=new ListNode(-1);
        Head->next=head;
        pre=Head;
        now=head;
        while(now&&now->next)
        {
            if(now->val == now->next->val)
            {
                while(now->next && now->val == now->next->val)
                {
                    now=now->next;
                }
                pre->next=now->next;
                now=now->next;
            }
            else 
            {
                pre=now;
                now=now->next;
            }
        }
        head=Head->next;
        delete(Head);
        return head;
    }
};

  

原文地址:https://www.cnblogs.com/qiaozhoulin/p/4775306.html