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

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    相对于Remove Duplicates from Sorted List这个问题,这个问题是要把重复出现过的所有元素全部删除。我的想法是找出每一个数字段的起点和终点,如果这个数据段出现了重复元素,就把这个数据段整体删除。

     1 public class Solution {
     2     public ListNode deleteDuplicates(ListNode head) {
     3         if(head==null || head.next==null) return head;
     4         ListNode thead = new ListNode(-1);
     5         ListNode begin = thead;
     6         ListNode end = head;
     7         thead.next = head;
     8         
     9         int cur = head.val;
    10         while(end.next!=null){
    11             if(end.next.val==cur){
    12                 end = end.next;
    13             }
    14             else{
    15                 if(begin.next==end){
    16                     begin = end;
    17                     end = end.next;
    18                 }
    19                 else{
    20                     begin.next = end.next;
    21                     end = begin.next;
    22                 }
    23                 cur = end.val;
    24             }
    25         }
    26         if(begin.next==end) return thead.next;
    27         begin.next = null;
    28         return thead.next;
    29     }
    30 }
     
  • 相关阅读:
    [bzoj1089] 严格n元树
    [bzoj1097] 旅游景点atr
    [hdu3887] Counting Offspring
    [POJ3321] Apple Tree
    [POJ3635] Full Tank?
    git
    【MySQL】数据的导出导入
    Ubuntu python 开发环境配置
    测试markdown
    约瑟夫环问题-java实现
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5403505.html
Copyright © 2011-2022 走看看