cpp
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;
}
};
- Node 有 3 个参数,val next 和 random
- 为了空间复杂度最优,在原来链表的节点之后插入一个节点,复制这个节点的 val next 和 random