138. 复制带随机指针的链表
题目描述
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or nullptr.
Return a deep copy of the list.
/**
* Definition for singly-linked list with a random pointer.
* struct Node {
* int val;
* Node *next, *random;
* Node(int x) : val(x), next(NULL), random(NULL) {}
* };
*/
代码实现
class Solution {
public:
Node *copyRandomList(Node *head) {
if(head == nullptr)
return nullptr;
Node *p = head;
//第一步
while(p!=nullptr)
{
Node *next = p->next;
Node *temp = new Node(p->val);
p->next = temp;
temp->next = next;
p = next;
}
//第二步
p = head;
while(p!=nullptr)
{
//根据程序的逻辑,P不为空,它后面紧跟复制节点p->next
//一定也不为空
Node *next = p->next->next;
if(p->random!=nullptr)
p->next->random = p->random->next;
p = next;
}
//第三步
Node *newHead = head->next;
p = head->next->next;
//尾指针的运用,由于我们这里没有借用头节点的技巧,所以这里,在进入循环前,先
//需要把第一个节点处理好,以做为尾节点使用
Node *last1 = head;
Node *last2 = head->next;
last1->next = nullptr;
last2->next = nullptr;
while(p!=nullptr)
{
Node *next = p->next->next;
last2->next = p->next;
last2 = last2->next;
last2->next = nullptr;
last1->next = p;
last1 = last1->next;
last1->next = nullptr;
p = next;
}
return newHead;
}
};