解题步骤:
- 首先复制各个节点,先拼接链表,在每个节点的后面插入与当前节点相同数据域的节点
- 然后将第一步插入的节点中random指针域分别指向当前节点的上一个节点的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:
Node* copyRandomList(Node* head) {
if(head == nullptr) return nullptr;
Node * cur = head;
//1、复制各节点,构建拼接链表
while(cur != nullptr)
{
Node * tmp = new Node(cur->val);
tmp->next = cur->next;
cur->next = tmp;
cur = tmp->next;
}
//2、构建新链表各节点的random指向
cur = head;
while(cur != nullptr)
{
if(cur->random != nullptr)
cur->next->random = cur->random->next;
cur = cur->next->next;
}
//3、拆分原/新链表
cur = head;
Node*new_list = cur->next;;
Node*new_list_head = cur->next;
while(new_list->next != nullptr)
{
cur->next = new_list->next;
new_list->next = cur->next->next;
cur = cur->next;
new_list = cur->next;
}
cur->next = nullptr;
return new_list_head;
}
};