普通链表复制
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* cur = head;
Node* dum = new Node(0), *pre = dum;
while(cur != nullptr) {
Node* node = new Node(cur->val); // 复制节点 cur
pre->next = node; // 新链表的 前驱节点 -> 当前节点
// pre->random = "???"; // 新链表的 「 前驱节点 -> 当前节点 」 无法确定
cur = cur->next; // 遍历下一节点
pre = node; // 保存当前新节点
}
return dum->next;
}
};
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == nullptr)
return nullptr;
unordered_map<Node*, Node*> res;
Node* cur = head;
while(cur!=nullptr)
{
res[cur] = new Node(cur->val);
cur = cur->next;
}
cur = head;
while(cur!=nullptr)
{
res[cur]->next = res[cur->next];
res[cur]->random = res[cur->random];
cur = cur->next;
}
return res[head];
}
};
链表拼接+拆分
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == nullptr)
return nullptr;
Node* cur = head;
//在原链表基础上拼接新链表 如 7-7-2-2-3-3-1-1
while(cur!=nullptr)
{
Node* tmp = new Node(cur->val);
tmp->next = cur->next;
cur->next = tmp;//这两句将tmp插入到原链表中即7-7-2-3-1
cur = tmp->next;//这两句将cur移向2即cur->next->next
}
//求新链表的random
cur = head;
while(cur!=nullptr)
{
if(cur->random != nullptr)
cur->next->random = cur->random->next; //左式中cur->next即复制好的新节点,右式中cur->random->next其值与cur->random相同,即新复制好的链表
cur = cur->next->next;
}
//拆分链表
cur = head->next;
Node* pre = head, *res = head->next;
while(cur->next != nullptr)
{
pre->next = pre->next->next;
cur->next = cur->next->next;
pre = pre->next;
cur = cur->next;
}
pre->next = nullptr;
return res;
}
};