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.

    Solution:

    代码分析取自: http://www.cnblogs.com/springfor/p/3862077.html

    使用3个指针(pre,cur,next)来遍历链表。

    同时还需要引入一个布尔型的判断flag,来帮助判断当前是否遇到有重复,这个flag能帮助识别是否需要删除重复。

     当没有遇到重复值(flag为false)时,3个指针同时往后移动:

     pre = cur;

     cur = next;

     next = next.next; 

    当遇到重复值时,设置flag为true,并让next一直往后找找到第一个与cur值不等的位置时停止,这时,cur指向的node的值是一个重复值,需要删除,所以这时就需要让pre的next连上当前的 next,这样就把所有重复值略过了。然后,让cur和next往后挪动继续查找。

    这里还需要注意的是,当next一直往后找的过程中,是有可能next==null(这种情况就是list的最后几个元素是重复的,例如1->2->3->3->null),这时cur指向的值肯定是需要被删除的,所以要特殊处理,令pre的next等于null,把重复值删掉。其他情况说明最后几个元素不重复,不需要处理结尾,遍历就够了。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode deleteDuplicates(ListNode head) {
    14         if (head == null || head.next == null)
    15             return head;
    16 
    17         ListNode dummy = new ListNode(-1);
    18         dummy.next = head;
    19 
    20         ListNode pre = dummy;
    21         ListNode cur = pre.next;
    22         ListNode next = cur.next;
    23         boolean isDuplicate = false;
    24         while (next != null) {
    25             if (cur.val == next.val) {
    26                 next = next.next;
    27                 isDuplicate = true;
    28                 if(next==null)
    29                     pre.next=null;
    30             } else {
    31                 if (!isDuplicate) {
    32                     pre = cur;
    33                     cur = next;
    34                     next = next.next;
    35                 }else{
    36                     pre.next=next;
    37                     cur=next;
    38                     next=next.next;
    39                     isDuplicate=false;
    40                 }
    41             }
    42         }
    43         return dummy.next;
    44     }
    45 }
  • 相关阅读:
    小程序登陆流程解析
    小程序连续点击bug解决
    小程序开发文本空格的添加
    微信小程序转支付宝小程序
    支付宝小程序开发入门
    微信小程序开发入门
    text属性
    小程序横向滚动
    will-change
    Docker 系列二(操作镜像).
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4104821.html
Copyright © 2011-2022 走看看