LeetCode::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.


这道题目是前一个题目的进化版,由于重复了的那个数字会被全部删去,这里面临一个多引入一个指针,来表征需要删除的节点的前一个节点,再多引入一个布尔值,
来标记到底这个数字是不是重复了;如果重复,位于pos 以及 next_pos之间的节点必须都删除(闭区间),pre_pos 很显然原地不动,当发现不是重复,那么pre_pos
向前走一格。
一个注意点:在思考链表类问题的时候,必须很明确每个指针标志着什么,并且需要再用到诸如a->next  a->val时特别确信a != NULL, 这个必须考虑到边界条件,如
何时走到了最后,或者链表只有一个节点或者没有节点,出现了特殊情况等等,这个是RUNTIME ERROR的关键问题


<span style="font-family: Arial, Helvetica, sans-serif;">ListNode *deleteDuplicates(ListNode *head) {</span>
        if (head == NULL || head->next == NULL)
            return head;
            
        bool isDup;
        ListNode *pos = head, *next_pos = head;
            
        ListNode *pre_pos = new ListNode(0);
        ListNode *new_head = pre_pos;
        pre_pos->next = head;
        
        while (next_pos != NULL)
        {
            next_pos = next_pos->next;
            isDup = false;
            while (next_pos != NULL && pos->val == next_pos->val)
            {
                isDup = true;
                next_pos = next_pos->next;
            }
            if (isDup)
            {
                pre_pos->next = next_pos;
                pos = next_pos;
            }
            else
            {
                pre_pos = pre_pos->next;
                pos = pos->next;
            }
        }
        return new_head->next;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值