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
.
思路:两个指针,一个pre,一个cur,一前一后,当pre的值等于cur的值时,pre不动,cur向前移动
代码:
/**
* 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) {
ListNode *pre=NULL,*cur=head;
if(head==NULL) return NULL;
pre=cur;
cur=cur->next;
if(cur==NULL) return pre;
while(cur!=NULL){
while(pre->val==cur->val){
cur=cur->next;
pre->next=cur;
if(cur==NULL) return head;
}
pre=cur;
cur=cur->next;
}
return head;
}
};