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

Remove Duplicates from Sorted List (链表)

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

标签:style   blog   io   color   ar   for   sp   div   on   

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 (链表)

标签:style   blog   io   color   ar   for   sp   div   on   

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

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