这道题还挺复杂的,主要是因为该单链表带随机指针
解题思路分成三步:①拷贝原节点并将每一个节点链接到原来节点的后面 ②处理拷贝节点的random指针:拷贝节点的random指针指向被拷贝节点随机指针的下一个位置 ③拆解链表,把拷贝链表从原链表中拆解处来,再连接拷贝链表
/*
// 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) {
//1.拷贝节点连接到原节点的后面
Node* cur = head;
while(cur != nullptr)
{
Node* copy = new Node(cur->val);
Node* next = cur->next;
cur->next = copy;
copy->next = next;
cur = next;
}
//2. 置random
cur = head;
while(cur)
{
Node* copy = cur->next;
if(cur->random == nullptr)
{
copy->random == nullptr;
}
else
{
copy->random = cur->random->next;
}
cur = cur->next->next;
if(copy->next)
{
copy = copy->next->next;
}
}
//3.拆解拷贝链表,再链接
cur = head;
Node* copyHead,*copyTail;
copyHead = copyTail =new Node(0);
while(cur)
{
Node* copy = cur->next;
Node* next = copy->next;
cur->next = next;
//尾插
copyTail->next = copy;
copyTail = copy;
cur = next;
}
Node* copyList = copyHead->next;
delete copyHead;
return copyList;
}
};