这道题写了很久,也的确是写的很难受很难受,先上一下我的代码,说明思路。
struct ListNode* deleteDuplicates(struct ListNode* head){
if (!head||!head->next) return head;//剔除掉无需操作的过短链表
//因为采用快慢指针,考虑链表相对较短情况的边界情况。
//链表长度为2的特殊情况
if (!head->next->next)
{if (head->val==head->next->val) return NULL;
else return slow;
}
//定义快慢指针,慢指针比快指针落后两个节点,判断慢指针下一个节点与快指针当下节点的相等关系
struct ListNode*slow=head;
struct ListNode*phead=slow;
struct ListNode*quick=head->next->next;
//key用来判定边界条件,例如[1,1,2]的链表返回值[1,1]故需要返回链表的下下节点,[1,1,1]返回[1,3]故需要返回链表下节点。这两种情况是因为,头节点没有被指向,故相等值的判定是从第二个节点开始的,且快指针在第三个节点位置,故一二节点相等无法被检测。
int key=0;
if (head->val==head->next->val)
{ if (head->val==head->next->next->val) key=1;
else key=2;
}
while(quick!=NULL){
if(quick->val!=slow->next->val)
{
slow=slow->next;
quick=quick->next;
}
else
{
struct ListNode*temp=slow->next->next;
while (temp&&temp->val==quick->val)
{
temp=temp->next;
}
if (!temp) {slow->next=NULL;
if (key==1) {sloww=sloww->next;}
if (key==2) {sloww=sloww->next->next;}
return sloww;}
else {slow->next=temp; quick=slow->next->next;}
}
}if (key==1) {phead=phead->next;}
if (key==2) {phead=phead->next->next;}
return sloww;
}
巴拉巴拉太麻烦了,其实在指针前加一个无用的头节点,就能解决一切问题
struct ListNode* deleteDuplicates(struct ListNode* head){
if (!head||!head->next) return head;
struct ListNode*slow=(struct ListNode*)malloc(sizeof(int)*4);
slow->val=0;
slow->next=head;
struct ListNode*sloww=slow;
struct ListNode*temp;
struct ListNode*quick=head->next;
while(quick!=NULL){
if(quick->val!=slow->next->val)
{
slow=slow->next;
quick=quick->next;
}
else
{
temp=slow->next->next;
while (temp&&temp->val==quick->val)
{
temp=temp->next;
}
if (!temp) {slow->next=NULL; return sloww->next;}
else {slow->next=temp; quick=slow->next->next;}
}
}
return sloww->next;
}