zoukankan      html  css  js  c++  java
  • Leetcode 138.复制带随机指针的链表

    复制带随机指针的链表

    给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

    要求返回这个链表的深度拷贝。 

    一种是按照原链表next的顺序依次创建节点,并处理好新链表的next指针,同时把原节点与新节点的对应关系保存到一个hash_map中,然后第二次循环将random指针处理好。这种方法的时间复杂度是O(n),空间复杂度也是O(n)。

     1 class Solution{
     2 public:
     3     RandomListNode *copyRandomList(RandomListNode *head){
     4         if (!head) return NULL;
     5         unordered_map<RandomListNode*, RandomListNode*> mp;
     6         //创建一个新的链表头
     7         RandomListNode *new_head = new RandomListNode(head->label);
     8         //node1负责指向原链表,node2负责指向新链表
     9         RandomListNode *node1 = head, *node2 = new_head;
    10         //按照原链表的结构不断创建新的节点,并维护好next指针,将node1与node2的对应关系保存在hash_map中,
    11         //以备后面维护random指针的时候,可以通过node1找到对应的node2。
    12         while (node1->next != NULL){
    13             mp[node1] = node2;
    14             node1 = node1->next;
    15             node2->next = new RandomListNode(node1->label);
    16             node2 = node2->next;
    17         }
    18         //将两个链表的尾巴的对应关系也保存好
    19         mp[node1] = node2;
    20         //继续从头开始处理random指针
    21         node1 = head;
    22         node2 = new_head;
    23         while (node1->next != NULL){
    24             node2->random = mp[node1->random];
    25             node1 = node1->next;
    26             node2 = node2->next;
    27         }
    28         //把尾巴的random指针也处理好
    29         node2->random = mp[node1->random];
    30         return new_head;
    31     }
    32 };
  • 相关阅读:
    hive 之only supports newline ' ' right now. Error encountered near token ''报错
    四、第三方图标库
    三、工具模块封装(二):封装mock模块
    三、工具模块封装(一):封装axios模块
    二、前端项目案例
    一、搭建前端开发环境(Vue+element)
    注册中心(Consul)
    系统服务监控(Spring Boot Admin)
    JWT
    Spring Security(四)
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10187866.html
Copyright © 2011-2022 走看看