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

    Example 1:

    Input: 1->2->3->3->4->4->5
    Output: 1->2->5

    Example 2:

    Input: 1->1->1->2->3
    Output: 2->3

    题意

    给定有序链表,凡有重复元素者,删光

    思路

    指针cur负责边扫旧链表边查重

    指针pre负责生成新链表

      

      

    代码

     1 class Solution {
     2       public ListNode deleteDuplicates(ListNode head) {
     3         if (head == null || head.next == null)  return head;
     4         ListNode dummy = new ListNode(-1);
     5         dummy.next = head;
     6         ListNode pre = dummy;
     7         ListNode cur = head;
     8 
     9         while (cur!= null) {
    10             // check duplicates
    11             while (cur.next != null && cur.val == cur.next.val) {
    12                 cur = cur.next;
    13             }
    14             // if cur != pre.next, it means cur moved and duplicates exist
    15             if (cur != pre.next) {
    16                 pre.next = cur.next;
    17             } else {
    18                 pre = pre.next;
    19             }
    20             cur = cur.next;
    21         }
    22         return dummy.next;
    23     }
    24 }
  • 相关阅读:
    wince5.0 key
    CSS基础知识思维导图xmind
    切图
    头部标签集
    List和Set的区别
    PicGo + Gitee 实现 Markdown 图床
    GitHub Pages 与 Gitee Pages 上的 Jekyll
    Agile, CI/CD,DevOps
    你还不了解DevOps? 看这篇就够了
    DevOps实践心得
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10955489.html
Copyright © 2011-2022 走看看