leetcode Remove Duplicates from Sorted List I && II

I

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) 
    {
       if(head==NULL)return NULL;
       ListNode *p=head;
       while(p&&p->next)
       {  
           ListNode *q=p->next;
           if(q->val==p->val)
           {
              if(q->next)
              {
                  p->next=q->next;
                  free(q);
              }
              else 
              {
                  p->next=NULL;
                  free(q);
              }
           }
           else p=p->next;
       } 
       return head;
    }
};

 II

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) 
    {
       if(head==NULL)return NULL;
       ListNode *p=head,*pre=head;
       bool flag=false;
       while(p)
       {  
           ListNode *q=p->next;
           while(q&&q->val==p->val)
           {
              flag=true;
              if(q->next)
              {
                  p->next=q->next;
              }
              else 
              {
                  p->next=NULL;
              }
              free(q);
              q=p->next;
           }
           if(flag==false)
           {
               pre=p;
               p=p->next; 
           }
           else
           {
               if(p==head)
               {
                   free(p);
                   p=q;  
                   head=p;
               }
               else 
               {
                   pre->next=q;
                   free(p);
                   p=q;  
               } 
               flag=false;
           }
       }
       return head;
    }
};
原文地址:https://www.cnblogs.com/tgkx1054/p/3099354.html