码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted List II

时间:2015-05-04 22:08:50      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:leetcode   remove duplicates   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.

算法:

前一段时间做这道题目的时候,思路是找到数字重复出现的start和end节点,把这一段的节点全部删掉,今天又重新做了,觉得可以使用last节点表示访问过的节点的值,并且用一个计数器计算出现的次数,如果次数大于1,就扔掉好了。


/**
 * 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)
            return NULL;
        ListNode* last=NULL;//表示上次访问的节点
        int cnt=0;//上次访问的数字出现的次数
        ListNode*p, *h;
        p=head;
        h=NULL;
        ListNode*tail=NULL;
        while(p){
            ListNode* next=p->next;
            p->next=NULL;
            if(last==NULL){//第一个节点
                last=p;
                cnt=1;
            }else if(p->val!=last->val){
                if(cnt==1){//只出现1次,不重复
                    if(!h){
                        h=last;
                        tail=h;
                    }else{
                        tail->next=last;
                        tail=tail->next;
                    }
                    last=p;//更新last
                    cnt=1;
                }else{
                    last=p;//last的值多次出现,重复的数字要扔掉,last换成新值
                    cnt=1;
                }
            }else{//p->val==s.top()->val
                cnt++;//计算重复的次数
            }
            p=next;
        }
        if(cnt==1){//别忘了最后的节点
            if(!h){
                h=last;
            }else{
                tail->next=last;
            }
        }
        return h;
    }
};








Remove Duplicates from Sorted List II

标签:leetcode   remove duplicates   sorted list ii   

原文地址:http://blog.csdn.net/u010786672/article/details/45486439

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!