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;  
        }  
    } 



  • 相关阅读:
    点击<a>页面跳转解决办法/跨域请求,JSONP
    笔记一下NODEJS建站
    地精排序Gnome Sort ----(排序算法十)
    鸡尾酒排序Cocktail Sort(排序算法九)
    鸽巢排序Pigeonhole Sort----(排序算法八)
    桶排序(Bucket Sort)----(排序算法七)
    堆排序----(排序算法六)
    简单选择排序算法----(排序算法五)
    快速排序----(排序算法四)
    冒泡排序法---排序算法(三)
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444476.html
Copyright © 2011-2022 走看看