82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

解答:我这么做很丑陋,但是要考虑很多情况,其实会有更好的做法的。

之所以temp=head->val+2;而不是加减1,是因为要解决第一个数是INT_MIN,第二个数是INT_MAX的问题,因为最小值减一就是最大值。

/**
 * 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) {
        ListNode* newhead=new ListNode(0);
        ListNode* p=newhead;
        newhead->next=NULL;
        int temp;
        if(head&&head->next)
        {
            if(head->val>head->next->val)
                temp=head->val+2;
            else
                temp=head->val-2;
        }
        while(head)
        {
           if((head->val!=temp))
           {
               if(head->next)
               {
                 if((head->val!=head->next->val))
                 {
                    p->next=head;
                    p=p->next;
                 }
                 else
                 {
                    temp=head->val;
                 }
               }
               else
               {
                   p->next=head;
                   p=p->next;
               }
           }
           else
           {
               temp=head->val;
           }
           head=head->next;
        }
        p->next=NULL;

        return newhead->next;
    }
};

二刷时发现这个做法更好,其实我也没怎么做出来的。

要注意
精妙之处在于

”’
if(pre->next==cur)
else
”’
这条语句。
这是用来判断我们要链接的下一个节点是经过很多次重复节点往前走得来的,还是说没有重复节点,要连接。

/**
 * 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) {
        ListNode* newhead= new ListNode(0);
        ListNode* pre=newhead;
        newhead->next=head;
        while(pre->next)
        {
            ListNode* cur=pre->next;
            while(cur->next&&cur->next->val==cur->val) cur=cur->next;
            if(pre->next==cur) pre=pre->next;
            else pre->next=cur->next;  
        }
        return newhead->next;


    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值