主要思路
方法一:map映射
首先建立对应结点 ,key值为旧的结点,value为相对应的新结点;
建立next和random连接即可
方法二:先拼接在拆分
先进行连接,连成1 1’ 2 2’ 3 3’…的形式 1’为1的复制
然后连接random
最后拆分 详见代码
class Node {
public:
int val;
Node* next;
Node *random;
Node(int _val) {
val = _val;
next = nullptr;
random = nullptr;
}
};
//方法一 map映射
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head==nullptr)return nullptr;
map<Node*,Node*> nnMap;
Node* cur= head;
while(cur) {//建立对应的新结点
nnMap[cur] = new Node(cur->val);
cur = cur->next;
}
cur = head;
while(cur!=nullptr) {
nnMap[cur]->next = nnMap[cur->next];
nnMap[cur]->random = nnMap[cur->random];
cur= cur->next;
}
return nnMap[head];
}
};
//方法二 拼接拆分
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head==nullptr)return nullptr;
Node *p = head;
while(p!=nullptr) {//先进行连接,连成1 1' 2 2' 3 3'...的形式 1'为1的复制
Node *tmp = new Node(p->val);
tmp->next = p->next;
p->next = tmp;
p = tmp->next;
}
p = head;
while(p!=nullptr) {//再连接random
if(p->random) {
p->next->random = p->random->next;
}
p = p->next->next;
}
//最后拆分
p = head->next;
Node *cur = head;
Node *ret = head->next;
while(p->next!=nullptr) {//新链表就两个结点的话就直接拆了 不进入循环
cur->next = cur->next->next;//原链表
p->next = p->next->next;//拆分出的新链表
cur = cur->next;
p = p->next;
}
cur->next =nullptr;
return ret;
}
};