Monday, 21 December 2015

LeetCode Remove Duplicates from Sorted List II

LeetCode 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 || head->next==NULL)

       return head;

     ListNode * current=head->next;

     ListNode * p=NULL;

     ListNode * prev=head;

     while(current!=NULL){

          if(current->val==prev->val)

          {

           prev=current;

           current=current->next;

          }

         else

         {

            if(p!=NULL)

              {

                if(p->next!=prev)

                  p->next=current;

                else

                  p=prev;

              }

            else

              {

                if(prev->val==head->val && prev!=head)

                 {

                  head=current;

                  p=NULL;

                 }

                else

                  p=prev;

              }

            prev=current;

            current=current->next;

         }

     }

     if(p==NULL && prev!=head && prev->val==head->val)

      return NULL;

     else if(p!=NULL){

      if(p->next!=prev)

         p->next=current;

     }

     return head;

    }

};

No comments:

Post a Comment