Remove Duplicates from Sorted List II

/**
 * 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) return head;
        if(head->next ==NULL) return head;
        ListNode *res = head;
        
        int head_val;

        while(head){
        head_val = head->val;
        if(head->next && head ->next->val == head_val){
        while(head && head->val == head_val)  //去掉开头重复的
         {
              head =head->next;
         }
        }
        else break;
        }
        res=head;
   
        //如果重复的部分不是在开头,需要记录pre结点。这里特别要注意逻辑性,head只有在后续结点不是重复结点的情况下,才可以往后移动
        while(head){
            if(head->next == NULL) break;
            ListNode* p_i = head->next;
            int next_val = p_i->val;
            if(p_i!=NULL &&p_i->next!=NULL && p_i->next->val == next_val){
            while(p_i && p_i->val ==next_val)
             {
                p_i =p_i->next;
             }
            if(p_i == NULL) {head->next=NULL;break;}
            head->next = p_i;
            }
            else head = p_i;
        }
        
        return res;
    }
 
};
原文地址:https://www.cnblogs.com/julie-yang/p/4691691.html