首页 > 代码库 > Remove Duplicates from Sorted List (链表)

Remove Duplicates from Sorted List (链表)

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