微软面试题: LeetCode 138. 复制带随机指针的链表 出现次数:3

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 class Solution {
 5 public:
 6     Node* copyRandomList(Node* head)
 7     {
 8     //第一步:遍历原链表生成新链表,同时用哈希表 memo 存储原链表和新链表对应节点之间的映射关系;
 9     //第二步:再次遍历原链表,根据原链表每个节点的随机指针和memo,在维护新链表的随机指针;
10         if(head == NULL)
11         {
12             return NULL;
13         }
14         unordered_map<Node*,Node*> memo;//原节点--> 对应的新生成节
15         Node* copy_head = new Node(head->val);
16         memo[head] = copy_head;
17         Node* front_ptr = copy_head;
18         Node* work_ptr = head->next;
19         while (work_ptr != NULL)
20         {
21             Node* tmp_ptr = new Node(work_ptr->val);
22             front_ptr->next = tmp_ptr;
23             front_ptr = tmp_ptr;
24             memo[work_ptr] =  tmp_ptr;
25             work_ptr = work_ptr->next;
26         }
27         work_ptr = head;
28         while (work_ptr != NULL)
29         {
30             if(work_ptr->random != NULL)
31             {
32                 memo[work_ptr]->random = memo[work_ptr->random]; 
33             }
34             work_ptr = work_ptr->next;
35         }
36         return copy_head;
37     }
38 };

 

上一篇:My Work


下一篇:itest work 开源接口测试&敏捷测试管理平台 9.5.0 GA_u1,优化及修复关键 BUG