Tuesday, October 27, 2015

Leetcode:delete all duplicate nodes

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.
---------------------------------------------------

1. Using dummy node as the head may be deleted.
2. note the following two cases:

  •      define a int val to guarantee all duplicates are deleted. 
  •      define a pointer p to cover two nodes, note the boundary check



///////////////////////////////////////
//code
class Solution {
public:
       ListNode* deleteDuplicates(ListNode* head) {
              //check input
              if (head == NULL)return head;
              ListNode *dum = new ListNode(-1), *tmp = head, *p = head;
              dum->next = head;
              p = dum;
              int val = INT_MAX;
              while (p->next->next != NULL){
                     if (p->next->val == p->next->next->val || p->next->val == val){
                           val = p->next->val;
                           tmp = p->next;
                           p->next = tmp->next;
                           delete tmp;
                     }
                     else p = p->next;
              }
              //delete left val
              if (p->next->val == val){
                     tmp = p->next;
                     p->next = tmp->next;
                     delete tmp;
              }
              head = dum->next;
              delete dum;
              return head;
       }

};

No comments:

Post a Comment