class Solution {
public:
Node* copyRandomList(Node* head) {
if ( !head ) return nullptr;
Node *cur = head;
while ( cur ) {
Node *copy = new Node( cur->val ); // 复制节点的值
copy->next = cur->next, cur->next = copy, cur = copy->next; // 把复制的节点插在两个节点之间
}
cur = head;
while ( cur ) {
Node *copy = cur->next;
copy->random = cur->random ? cur->random->next : nullptr; // 把复制的节点的 random 指针建立起来
cur = copy->next;
}
cur = head;
Node *newHead = head->next, *copyCur = newHead;
while ( cur ) {
cur->next = copyCur->next, cur = cur->next; // 拆分两个链表
if ( cur ) copyCur->next = cur->next, copyCur = copyCur->next;
}
return newHead;
}
};