作者:日出等日落
专栏:leetCode刷题训练
只有一条路不能选择—那就是放弃的路;只有一条路不能拒绝—那就是成长的路。
今天我来讲一下力扣138题. 复制带随机指针的链表
138. 复制带随机指针的链表 - 力扣(Leetcode)
目录
题目:
这道题解法分为三个步骤:
- 在原结点的基础上再拷贝一份结点,每一个结点和原来的结点一样连接到一起
- 设置拷贝结点的random值
- 拷贝结点解下去,并链接组成新的链表,最后将原结点恢复
第一步:
代码展示:
struct Node* cur=head;
while(cur)
{
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
struct Node* next = cur->next;
copy->val = cur->val;
//插入
cur->next = copy;
copy->next = next;
cur = next;
}
第二步:
代码展示:
cur = head;
while(cur)
{
struct Node* copy = cur->next;
//struct Node* next = copy->next;
if(cur->random == NULL)
{
copy->random = NULL;
}
else
{
copy->random = cur->random->next;
}
cur=cur->next->next;
}
第三步:
代码展示:
cur= head;
struct Node* newhead = NULL , *newtail =NULL;
while(cur)
{
struct Node* copy = cur->next;
struct Node* next = copy->next;
cur->next = next;
if(newtail == NULL)
{
newhead = newtail = copy;
}
else
{
newtail->next = copy;
newtail = newtail->next;
}
cur = next;
}
return newhead;
}