标签:关系 alt code lan 有一个 图片 solution 思路 函数
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
输入: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出: [[7,null],[13,0],[11,4],[10,2],[1,0]]
class Solution {
public:
Node* copyRandomList(Node* head) {
unordered_map<Node*, Node*> ump;
Node* cur = head;
while (cur) {
Node* node = new Node(cur->val);
ump[cur] = node;
cur = cur->next;
}
cur = head;
while (cur) { // 新生成的节点通过哈希表建立关系
ump[cur]->next = ump[cur->next];
ump[cur]->random = ump[cur->random];
cur = cur->next;
}
return ump[head];
}
};
链表的深拷贝问题,因为涉及random指针,可以将新建立的节点与原始节点通过哈希表建立一一对应关系。
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return NULL;
Node* cur = head;
while (cur) { // 链表复制阶段
Node* node = new Node(cur->val);
node->next = cur->next;
cur->next = node;
cur = node->next;
}
Node* res = head->next;
cur = head;
while (cur) { // random赋值阶段
if (cur->random) cur->next->random = cur->random->next;
cur = cur->next->next; // cur存在时cur->next一定存在
}
Node* pre = head;
cur = pre->next;
while (cur->next) { // 链表拆分阶段
pre = pre->next = cur->next;
cur = cur->next = pre->next;
}
pre->next = NULL;
return res;
}
};
需要三次遍历:
标签:关系 alt code lan 有一个 图片 solution 思路 函数
原文地址:https://www.cnblogs.com/tmpUser/p/14459059.html