leetcode-82. 删除排序链表中的重复元素 II

这道题写了很久,也的确是写的很难受很难受,先上一下我的代码,说明思路。

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值