题目来源
1、将每个 拷贝节点 都 插入 在原来的节点的后面
2、链接每个拷贝结点的 random
注意:
3、将拷贝结点 解 下来,尾插到一起,恢复原来链表。
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* copyRandomList(struct Node* head) {
//1 将每个 拷贝节点 都 插入 在原来的节点的后面
struct Node* cur = head;
while(cur){
struct Node* next = cur->next;
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
//拷贝结点的值和cur的值相同
copy->val = cur->val;
//将拷贝结点插入在cur的后面
cur->next =copy;
copy->next = next;
//往后走
cur = next;
}
//2 链接每个拷贝结点的 random
cur = head;
while(cur){
struct Node* copy = cur->next;
//链接random
if(cur->random == NULL)
copy->random = NULL;
else
copy->random = cur->random->next;//注意
cur = copy->next;
}
//3 将拷贝结点 解 下来,尾插到一起,恢复原来链表。
cur = head;
struct Node* copyhead = NULL;
struct Node* copytail = NULL;
while(cur){
struct Node* copy = cur->next;
struct Node* next = copy->next;
//最开始为空
if(copytail == NULL)
copyhead = copytail = copy;
else{
copytail->next = copy;
copytail = copytail->next;
}
//恢复原来的链表
cur->next = next;
//注意
cur = next;
}
return copyhead;
}