Disclaimer: This article is written self-study, pointed out that if the error also hope, thank you ^ - ^ https://blog.csdn.net/weixin_43871369/article/details/91397921
Title Description
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinctnumbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.
//Solution 1
//最简单的办法莫过于重新建立一个链表
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head==NULL||head->next==NULL) return head;
ListNode *newList=new ListNode(-1);
ListNode *p=newList,*q=head;
bool isdup=false;
while(q!=NULL)
{
while(q!=NULL&&q->next!=NULL&&q->val==q->next->val)
{
isdup=true;
q=q->next;
}
if(isdup) isdup=false;
else{
p->next=q;
p=p->next;
}
if(q!=NULL) q=q->next;
}
if(p!=NULL) p->next=NULL;
return newList->next;
}
};
//Solution 2-Recursive
//对于链表首先要想到递归,递归将会很简单
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head==NULL||head->next==NULL) return head;
ListNode *ptr=head;
if(ptr->val!=ptr->next->val)
{
ptr->next=deleteDuplicates(ptr->next);
return ptr;
}
while(ptr!=NULL&&ptr->next!=NULL&&ptr->val==ptr->next->val)
ptr=ptr->next;
if(ptr==NULL||ptr->next==NULL) return NULL;
return deleteDuplicates(ptr->next);
}
};
Expand version:
Title Description
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.
//non-recursive
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head==NULL||head->next==NULL) return head;
ListNode *pre,*pp;
pre=head;
pp=head->next;
while(pp!=NULL)
{
while(pp!=NULL&&pp->val==pre->val)
{
pre->next=pp->next;
delete pp;
pp=pre->next;
}
if(pp==NULL) break;
pre=pp;
pp=pre->next;
}
return head;
}
};
//recursive
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head==NULL||head->next==NULL) return head;
ListNode *del=head->next;
while(del!=NULL&&head->val==del->val)
{
head->next=del->next;
delete del;
del=head->next;
}
head->next=deleteDuplicates(head->next);
return head;
}
};