[LeeCode] 82. Remove Duplicates from Sorted List II java

    /**82. Remove Duplicates from Sorted List II
     * @param head
     * @return 出现次数>=2的数字全不要
     */
    public ListNode deleteDuplicates2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode ret = new ListNode(-1);
        ret.next = head;

        ListNode pre = ret;
        ListNode cur = pre.next;
        ListNode post = cur.next;
        boolean flag = false;
        while (post != null) {
            if (cur.val == post.val) {
                flag = true;
                post = post.next;
                if (post == null) {
                    pre.next = null;
                }
            } else {
                if (flag) {
                    pre.next = post;
                    flag = false;
                } else {
                    pre = cur;
                }
                cur = post;
                post = post.next;
            }
        }
        return ret.next;
    }
    /**三个指针,pre cur post
     * 引入一个布尔型的判断flag,来帮助判断当前是否遇到有重复,这个flag能帮助识别是否需要删除重复
     * 当没有遇到重复值(flag为false)时,3个指针同时往后移动
     * 当遇到重复值时,设置flag为true,并让post一直往后找找到第一个与cur值不等的位置时停止,
     *   这时,cur指向的node的值是一个重复值,需要删除,所以这时就需要让pre的next连上当前的post,这样就把所有重复值略过了。
     *  然后,让cur和post往后挪动继续查找。
     * */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值