请实现 copyRandomList
函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next
指针指向下一个节点,还有一个 random
指针指向链表中的任意节点或者 null
。
思路:
三步走,先复制当前的复杂链表,如1->2->3,复制为1->1(copy)->2->2(copy)->3->3(copy)。然后,调整复制链表里的random指针,如果节点1的random指针存在,比如1->random = 3,则1(copy)->random = 1->random->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:
void copyList(Node* head) {
Node* tmp = head;
while(tmp) {
Node* newT = new Node(tmp->val);
newT->next = tmp->next;
tmp->next = newT;
tmp = tmp->next->next;
}
}
void designateRandomNode(Node* head) {
Node* tmp = head;
while (tmp) {
if (tmp->random) {
tmp->next->random = tmp->random->next;
}
tmp = tmp->next->next;
}
}
Node* splitRandomNode(Node* head) {
Node* newHead = head->next;
Node* tmp = head;
while (tmp) {
Node* nextN = tmp->next;
tmp->next = tmp->next->next;
tmp = tmp->next;
if (nextN->next) {
nextN->next = nextN->next->next;
nextN = nextN->next;
}
}
return newHead;
}
Node* copyRandomList(Node* head) {
if (head == nullptr) {
return nullptr;
}
copyList(head);
designateRandomNode(head);
return splitRandomNode(head);
}
};