zoukankan      html  css  js  c++  java
  • 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.

     

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    //思路有点像2号的题,pre类似non_dup_end,但有很大的区别
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if (head==null) return head;
            
            ListNode newhead = new ListNode(Integer.MIN_VALUE);   //设置一个新head,并保证新head的值不会与后面的节点的值重复
            newhead.next = head;
            ListNode pre = newhead;
            ListNode cur = head;
            ListNode next = head.next;
            boolean dup = false;          //用来标志有重复的标志位
            
            while (next!=null) {
                if (cur.val!=next.val) {
                    if (dup) {           //处理上次循环遗留下来的重复问题
                        pre.next = next; //把所有中间重复的节点都删除
                        dup = false;     //重写标志位
                    }else{
                        pre = cur;       //在删除了中间所有的重复节点之后,pre是不向后移位的,只有不需要处理重复时,才向后移
                    }
                    cur = next;
                    next = next.next;
                }
                else{                    // cur.val==next.val
                    dup = true;          //如果发现了重复,本次循环只是把dup标志位true,并把next向后移一位,pre与cur并不向后移
                    next = next.next;    //对于重复的删除操作是直至向后找到cur!=val时再进行节点删除操作
                }
            }
            if (dup) pre.next = next;   //当while循环之后,next为null,若此时dup=true,说明最后几个元素师重复的,但无法进入到while处理  
            return newhead.next;  
        }  
    } 



  • 相关阅读:
    contest hunter5105 Cookies
    bzoj2599: [IOI2011]Race
    poj1741 Tree
    bzoj2527: [Poi2011]Meteors
    bzoj3673: 可持久化并查集 by zky&&3674: 可持久化并查集加强版
    bzoj2741: 【FOTILE模拟赛】L
    bzoj3110: [Zjoi2013]K大数查询
    bzoj1901: Zju2112 Dynamic Rankings
    bzoj2821: 作诗(Poetize)
    poj1417 True Liars
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444476.html
Copyright © 2011-2022 走看看