• 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 };
  • 相关阅读:
    URAL 1658. Sum of Digits(DP)
    HDU 4433 locker(SPFA+DP)
    Vijos 1092 全排列
    POJ 1141 Brackets Sequence(DP)
    HDU 4597 Play Game
    HDU 1693 Eat the Trees(插头DP)
    USACO 5.4 Twofive(DP)
    USACO 5.5 Hidden Password(搜索+优化)
    USACO 5.5 Picture(周长并)
    USACO 5.4 Telecowmunication(最大流+枚举)
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646630.html
Copyright © 2020-2023  润新知