哈希
- 两步走
- 第一次赋值val和next,构造哈希表 key:旧链表结点,value对应位置的新链表的结点
- 第二次重新从头走一遍,通过哈希表记住random:
- 新链表和旧链表同时移动,旧链表当前指针作为key,value为当时和对应的新链表
- 与此同时 dic[旧链表当前指针->random]即为对应的新链表当前指针->random
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* start = new Node(0);
Node* s2 = start;
Node* cur = head;
unordered_map<Node*, Node*> m;
while(cur!=nullptr){
start->next = new Node(cur->val);
start=start->next;
m[cur] = start;
cur=cur->next;
}
start = s2->next;
cur = head;
while(cur!=nullptr){
start->random = m[cur->random];
start=start->next;
cur=cur->next;
}
return s2->next;
}
};
拼接拆分
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == nullptr) return nullptr;
Node* cur = head;
while(cur != nullptr) {
Node* tmp = new Node(cur->val);
tmp->next = cur->next;
cur->next = tmp;
cur = tmp->next;
}
cur = head;
while(cur != nullptr) {
if(cur->random != nullptr)
cur->next->random = cur->random->next;
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;
}
};