首页 > 其他 > 详细

Remove Duplicates from Sorted List (链表)

时间:2014-11-06 19:29:35      阅读:198      评论:0      收藏:0      [点我收藏+]

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

思路:两个指针,一个指向当前节点cur,一个指向下一个节点nx,终止条件,也就是比较了len-1次。

比较若不等,则两指针均后移,若相等则删除节点,且cur指针不变,nx指针后移。

代码:

class Solution {
public:
    int getLength(ListNode *head){
        int length=0;
        while(head){
            ++length;
            head=head->next;
        }
        return length;
    }
    ListNode *deleteDuplicates(ListNode *head) {
        if(head==NULL) return NULL;
        int len=getLength(head);
        int i=1;
        ListNode* res=head;
        ListNode* cur=res;
        ListNode* nx=res->next;
        while(i<len){
            if(cur->val==nx->val){
                cur->next=cur->next->next;
                nx=nx->next;
            }else{
                cur=cur->next;
                nx=nx->next;
            }
            ++i;
        }
        return res;
    }
};

 

Remove Duplicates from Sorted List (链表)

原文:http://www.cnblogs.com/fightformylife/p/4079252.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!