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

     1 class Solution {
     2 public:
     3     ListNode *deleteDuplicates(ListNode *head) {
     4         return deleteDuplicates_1(head);
     5     }
     6     
     7     ListNode *deleteDuplicates_1(ListNode *head) {
     8         ListNode dummy(0), *cur = &dummy;
     9         dummy.next = head;
    10         while (cur->next)
    11         {
    12             ListNode *node = cur->next;
    13             int val = node->val;
    14             if (!node->next || node->next->val != val) {
    15                 cur = cur->next;
    16                 continue;
    17             }
    18             while (node && node->val == val) {
    19                 ListNode *del = node;
    20                 node = node->next;
    21                 delete del;
    22             }
    23             cur->next = node;
    24         }
    25         return dummy.next;
    26     }
    27     
    28     ListNode *deleteDuplicates_2(ListNode *head) {
    29         if (!head) return NULL;
    30         if (!head->next || head->val != head->next->val) {
    31             head->next = deleteDuplicates(head->next);
    32             return head;
    33         }
    34         int val = head->val;
    35         while(head && head->val == val) {
    36             ListNode *del = head;
    37             head = head->next;
    38             delete del;
    39         }
    40         return deleteDuplicates(head);
    41     }
    42 };
  • 相关阅读:
    HDOJ1213 并查集
    poj 3070 Fibonacci
    csu 1102 Palindrome
    C#格式化数值结果表
    正则表达式基础知识
    C#验证Email是否真正存在
    【翻译】Scott Mitchell的ASP.NET2.0数据教程中文版索引
    分块下载,测试文件 3.8GB
    asp.net的TextBox回车触发事件
    Cookie加密
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646630.html
Copyright © 2011-2022 走看看