删除一个链表里面重复出现过的元素。
11123 -〉 23
自己的思路:
/**
* 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* pre=new ListNode(0);
ListNode* p=head;
ListNode* q=head;
ListNode* first=new ListNode(0);
pre->next=head;
first->next=pre;
int flag;
while(q->next){
flag=0;
q=p->next;
while(q!=NULL && q->val==p->val){
q=q->next;
flag=1;
}
if(flag==1){
pre->next=q;
pre=pre->next;
}
else{
pre->next=p;
pre=pre->next;
}
//q=q->next;
}
return first->next->next;
}
};
最好的是递归的方法:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return 0;
if (!head->next) return head;
int val = head->val;
ListNode* p = head->next;
if (p->val != val) {
head->next = deleteDuplicates(p);
return head;
} else {
while (p && p->val == val) p = p->next;
return deleteDuplicates(p);
}
}
};