zoukankan      html  css  js  c++  java
  • [LeetCode]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 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* deleteDuplicates(ListNode* head) {
    12         if (!head || !(head->next)) return head;
    13         
    14         ListNode *p = head->next;
    15         if (head->val == p->val) {
    16             while (p && head->val == p->val) {
    17                 ListNode *tmp = p;
    18                 p = p->next;
    19                 delete tmp;
    20             }
    21             delete head;
    22             return deleteDuplicates(p);
    23         } else {
    24             head->next = deleteDuplicates(head->next);
    25             return head;
    26         }
    27     }
    28 };

     迭代版:2015-10-27

     1 class Solution {
     2 public:
     3     ListNode* deleteDuplicates(ListNode* head) {
     4         if (!head || !(head->next)) return head;
     5         
     6         ListNode dummy(-1);
     7         ListNode *prev = &dummy;
     8         ListNode *cur = head;
     9         bool isDuplicated = false;
    10         while (cur != nullptr) {
    11             isDuplicated = false;
    12             while (cur->next != nullptr && cur->val == cur->next->val) {
    13                 isDuplicated = true;
    14                 cur = cur->next;
    15             }
    16             
    17             if (isDuplicated) {
    18                 cur = cur->next;
    19                 continue;
    20             }
    21             
    22             prev->next = cur;
    23             prev = prev->next;
    24             cur = cur->next;
    25             
    26         }
    27         
    28         prev->next = cur;
    29         
    30         return dummy.next;
    31     }
    32 };
  • 相关阅读:
    负载均衡算法实现方式
    TCP三次握手和四次挥手
    深度解析Java内存原型
    缓存击穿、缓存穿透和缓存雪崩
    uni-app分包加载
    vuex的使用
    在web中打开exe程序并传参
    Vue 中引用高德地图
    .Net Core 从MySql数据库生成实体类 Entity Model
    vs2017 创建项目推送到Git上
  • 原文地址:https://www.cnblogs.com/skycore/p/4911929.html
Copyright © 2011-2022 走看看