【LeetCode】82 - Remove Duplicates from Sorted List II

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.

Failed solution : 不同于Remove Duplicates from Sorted List,II需要删除所有重复出现的节点,尝试过同时比较三个数,没有成功;

Solution 1:runtime 12ms

设置一个新的头节点newhead,比较newhead->next->val与cur->next->val,就变成了比较旧的头节点和第二个节点,直到找到与头节点val不等的节点,将newhead的next指向cur的next;如果cur==newhead->next, 则newhead移向下一个,

/**
 * 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 || !head->next )return head;
        ListNode *newhead=new ListNode(-1);
        newhead->next=head;
        ListNode *cur=head, *pre=newhead;
        while(cur){
            while(cur->next && pre->next->val==cur->next->val){
                cur=cur->next;
            }
            if(cur==pre->next)
                pre=pre->next;
            else
                pre->next=cur->next;
            cur=cur->next;
        }
        return newhead->next;
    }
};

 Solution 2:runtime 8ms

 设置一个temp变量记录重复节点的val, 删除所有val==temp的节点

/**
 * 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||!head->next)return head;
        ListNode *newhead=new ListNode(-1);
        ListNode *pre=newhead;
        int tmp;
        while(head && head->next){
          if(head->val!=head->next->val){
              pre->next=head;
              pre=pre->next;
              head=head->next;
          }
          else{
              tmp=head->val;
              while(head&&tmp==head->val)head=head->next;
          }
        }
        pre->next=head;
        return newhead->next;
    }
};

 

posted @ 2015-08-23 22:58  irun  阅读(169)  评论(0编辑  收藏  举报