题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
非递归:
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead==NULL || pHead->next==NULL){return pHead;}
ListNode* tmp=new ListNode(-1); //节点一定要初始化
tmp->next=pHead;
ListNode* pre = tmp;
ListNode* last = tmp->next;
while(last!=NULL){
if(last->next!=NULL&&last->val==last->next->val){
while(last->next!=NULL&&last->val==last->next->val){
last=last->next;
}
last=last->next;
pre->next=last;
}
else{
pre=pre->next;
last=last->next;
}
}
return tmp->next;
}
};
递归:
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead==NULL || pHead->next==NULL){return pHead;}
ListNode* tmp=new ListNode(-1); //节点一定要初始化
if(pHead->next!=NULL&&pHead->val==pHead->next->val){
tmp =pHead->next->next;
while(tmp&&pHead->val==tmp->val){
tmp=tmp->next;
}
return deleteDuplication(tmp);
}
else{
pHead->next=deleteDuplication(pHead->next);
return pHead;
}
return pHead;
}
};