1.第一题
138. 复制带随机指针的链表 - 力扣(LeetCode)
PS:可以自己理清楚这一题怎么写的就代表你的链表知识掌握程度以经到了9分,
因此这个题目的思维将是你需要重点掌握的东西。!!!!
思路分析:
用这个方法将分成三个步骤!
总体图如下:
第一步:将拷贝的节点放到原来节点的后面
细节如图
第二步:配置random,使得拷贝的节点的random和原来节点的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));
copy->val = cur->val;
//插入链接
cur->next = copy;
copy->next = next;
cur = next;
}
//配置random
cur = head;
while(cur)
{
struct Node * copy = cur->next;
if(cur->random == NULL)
{
copy->random = NULL;
}
else
{
copy->random = cur->random->next;
}
cur = cur->next->next;
}
//3.将复制链表解下来链接到一起,并且复原原链表
cur = head;
struct Node* copyHead = NULL;
struct Node* copyTail = NULL;
while(cur)
{
struct Node* copy = cur->next;
struct Node* next = copy->next;
//复原原链表
cur->next = next;
//尾插
if(copyTail == NULL)
{
copyHead = copyTail = copy;
}
else
{
copyTail->next = copy;
copyTail = copyTail->next;
}
cur = next;
}
return copyHead;
}