复制复杂链表
一、题目
以示例1
为例展开分析
二、思路分析
如果只是简单的复制,那么很简单
但题目要求复制链表中的指针都不应指向原链表中的节点
这就要求我们需要malloc
出和原链表相同的节点
而我们能做到的只是将新的节点链接起来,至于像原链表那样链接方式,却无法做到,因为新的链表不知道random是第几位
我们需要原链表的一个映射,去找到那个关系
⛄️第一步代码:
struct Node* copyRandomList(struct Node* head) {
struct Node* cur = head;
while(cur)
{
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
copy->val = cur->val;
copy->next = cur->next;
cur->next = copy;
cur = copy->next;
}
}
我们发现copy
需要的random
就是上一个节点->random->next
💨模拟第一步:
💨模拟第二步:
💨模拟第三步:
💨模拟第四步:
💨模拟第五步
最后再将这些代码尾插到新链表中
代码如下:
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* copyRandomList(struct Node* head) {
struct Node* cur = head;
while(cur)
{
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
copy->val = cur->val;
copy->next = cur->next;
cur->next = copy;
cur = copy->next;
}
cur = head;
while(cur)
{
struct Node* copy = cur->next;
if(cur->random == NULL)
{
copy->random = NULL;
}
else
{
copy->random = cur->random->next;
}
cur = copy->next;
}
struct Node* copyhead = (struct Node*)malloc(sizeof(struct Node));
struct Node* copytail = copyhead;
cur = head;
while(cur)
{
cur = cur->next;
copytail->next = cur;
copytail = cur;
if(cur == NULL)
{
break;
}
cur = cur->next;
}
copytail->next = NULL;
struct Node* ret = copyhead->next;
free(copyhead);
return ret;
}