【随机链表的复制】

题目

在这里插入图片描述

开始的错误思路

1.创建新的链表(单链表)
2.在新的链表上解决random的指向
(1)cur遍历原链表,newcur遍历新链表
(2)find是找到与原链表相同 val 的地址(错误之处就在这里:假如原链表有多个相同的val就错了)
时间复杂度:O(N*N)
空间复杂度:O(N)

代码

在这里插入图片描述
在这里插入图片描述

错误的原因

没有考虑到原链表有多个相同的val的节点存在

优化思路

要求时间复杂度:O(N)
steps:
1.把建立的新节点拷贝到原节点的后面
2.新节点的random就是原节点的random的下一个节点
3.新节点链在一起形成新链表,恢复原链表

画图更好理解:
在这里插入图片描述

代码

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {

if(head==NULL)
return NULL;
    //1.把建立的新节点拷贝到原节点的后面
	Node*cur=head;
    Node*next=cur->next;
    Node*copy;
    while(cur)
    {
        //创建新节点
       copy=(Node*)malloc(sizeof(Node));
        copy->val=cur->val;

        cur->next=copy;
        copy->next=next;

        cur=next;
        if(next)
        next=cur->next;
    }
    //2.解决random的指向 -->  copy->random=cur->random->next
    cur=head;
    while(cur)
    {
        copy=cur->next;

        if(cur->random==NULL)
        {
            copy->random=NULL;
        }
        else
        {
            copy->random=cur->random->next;
        }

        cur=cur->next->next;
       
    }
    //3.尾插+恢复
    cur=head;
   Node*newhead=NULL,*newtail=NULL;
    while(cur)
    {
        copy=cur->next;
        next=copy->next;

        if(newhead==NULL)
        {
            newhead=newtail=copy;
        }
        else{
            newtail->next=copy;
            newtail=newtail->next;
        }
        cur->next=next;

        cur=next;

    }
    return newhead;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值