只留下链表中出现了一次的节点。也只需要遍历一遍,只是要多用一个指针prere,当遇到出现两次以上的节点时方便回退。
/**
* 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==NULL||head->next==NULL) return head;
ListNode* prere=NULL;
ListNode* pre=head;
ListNode* p=head->next;
int tmp=head->val;
while(p){
if(p->val==tmp){
pre=prere;
p=p->next;
if(pre){
pre->next=p;
}
else{
head=p;
}
}
else{
tmp=p->val;
prere=pre;
pre=p;
p=p->next;
}
}
return head;
}
};