Monday, 21 December 2015

LeetCode Remove Duplicates from Sorted List

LeetCode  Remove Duplicates from Sorted List 

/**

 * 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* prev=head;

         ListNode* temp=NULL;

         while(current!=NULL){

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

             {

                 temp=current;

                 prev->next=current->next;

                 current=current->next;

                 free(temp);

             }

             else

             {

                 prev=current;

                 current=current->next;

             }

         }

         return head;

    }

};

No comments:

Post a Comment