给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的 深拷贝。
我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。
示例一:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
解题思路:
在链表的每一个元素后都插入一个该元素的复制;
根据前面的元素的指引来对random指向赋地址指向;
拆出复制的链表
实现代码:
struct Node* copyRandomList(struct Node* head) {
if(head == NULL) {
return NULL;
}
struct Node* cur = head;
struct Node* copy;
//复制节点,放于其后
while(cur) {
copy = copy = (struct Node*) malloc(sizeof(struct Node));
copy->val = cur->val;
copy->next = cur->next;
cur->next = copy;
copy->random = NULL;
cur = cur->next->next;
}
//调整random的指向
cur = head;
while(cur) {
copy = cur->next;
if(cur->random == NULL) {
copy->random = NULL;
}
else{
copy->random = cur->random->next;
}
cur = cur->next->next;
}
//拆链
cur = head;
while(cur) {
copy = cur->next;
cur = copy->next;
if(cur == NULL) {
copy->next = NULL;
}
else{
copy->next = cur->next;
}
}
return head->next;
}
运行结果: