一.题目
二.思路分析
1.将拷贝节点插入到原节点后面
拷贝节点和原节点建立了一个关联关系
2.深拷贝
3.将新节点拿下来尾插形成新链表,恢复原链表
三.参考代码
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* copyRandomList(struct Node* head) {
//指针cur遍历原链表
struct Node* cur = head;
while(cur)
{
//创建新节点(拷贝节点),插入到原链表
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->val = cur->val;
newnode->next = cur->next;
cur->next = newnode;
cur = newnode->next;
}
//重置cur到head,用来重新遍历链表
cur = head;
//进行深拷贝random
while(cur)
{
struct Node* copy = cur->next;
if(cur->random == NULL)
{
copy->random = cur->random;//NULL
}
else
{
copy->random = cur->random->next;//关键句
}
cur = copy->next;
}
//重置cur到head
cur = head;
//把新节点拿下来尾插成为新链表,并修复原链表
struct Node* copyhead = NULL,*copytail =NULL;
while(cur)
{
struct Node* copy = cur->next;//每次都是新建立的节点
struct Node* next = copy->next;//创建指针指向copy的next指针(位于原链表),便于修复原链表
if(copytail != NULL)
{
copytail->next = copy;
copytail = copytail->next;
}
else
{
copyhead = copytail = copy;
}
cur->next = next;//恢复原链表
cur = next;//cur移到原链表的下一位
}
return copyhead;
}