zoukankan      html  css  js  c++  java
  • 82.Remove Duplicates from Sorted List II

    题目链接

    题目大意:删除有序单链表中所有重复的数字,将非重复的数字留下来。与83有点 区别。

    法一:记录前面的重复节点,将当前结点与下一个节点和上一个重复节点进行比较,(因为可能出现3->3->3的情况),如果都不重复,则将节点保留,其他重复节点都删除。代码如下(耗时1ms):

     1     public ListNode deleteDuplicates(ListNode head) {
     2         //pre记录前面最后一个重复的结点,cur进行遍历
     3         ListNode res = null, cur = res, pre = null;
     4         while(head != null) {
     5             //如果前后节点重复则跳过,即删除
     6             if(head.next != null && head.val == head.next.val) {
     7                 pre = head;
     8                 head = head.next.next;
     9             }
    10             //如果当前节点与上一个节点重复,则删除
    11             else if(pre != null && head.val == pre.val) {
    12                 head = head.next;
    13             }
    14             //如果不重复,则将结点保留
    15             else {
    16                 //尾插
    17                 if(cur == null) {
    18                     cur = head;
    19                     res = cur;
    20                 }
    21                 else {
    22                     cur.next = head;
    23                     cur = head;
    24                 }
    25                 head = head.next;
    26             }
    27         }
    28         if(cur == null) {
    29             return null;
    30         }
    31         cur.next = null;
    32         return res;
    33     }
    View Code
  • 相关阅读:
    函数的对称性及其图像变换
    KMP 字符串匹配
    15 保护模式中的特权级(上)
    每日总结
    每日总结
    每日总结
    每日总结
    每日总结
    每日总结
    2-26安卓自学
  • 原文地址:https://www.cnblogs.com/cing/p/9182057.html
Copyright © 2011-2022 走看看