链表oj-随机链表的复制

目录

题目:

解题思路:

如何处理每个节点的random指针:

解题代码:


题目:

138. 随机链表的复制 - 力扣(LeetCode)

解题思路:

实际上这道题中,拷贝链表并不难,就遍历一遍,按照原链表对应的值去malloc就好了,但难点就在于如何处理每个节点的random指针。

如何处理每个节点的random指针:

因为每个节点的random指针的指向是不确定的,所以我们可以在原链表中的两两节点中间加入我们的copy节点,通过原链表的相对位置来找到我们copy的链表中各个节点random指针对应的相对位置,如果原链表中的random指针指向不为NULL时,那么对应的copy节点的random指针就指向了源节点的random->next的位置。

解题代码:

struct Node* copyRandomList(struct Node* head) {
    if(head==NULL)
    return NULL;
	struct Node* cur =head;
     struct Node* copy=NULL;
     //拷贝每个节点并嵌入到两个原节点中间
    while(cur)
    {
        copy =(struct Node*)malloc(sizeof(struct Node));
        copy->val=cur->val;
        copy->next=cur->next;
        cur->next=copy;
        cur=copy->next;
    }

    cur=head;
   

    //处理random指针
    while(cur)
    {
        copy=cur->next;
        if(cur->random)
        copy->random=cur->random->next;
        else
        copy->random=NULL;
        cur=copy->next;
    }


    //穿起copy节点
    cur=head->next;
    struct Node* newhead=(struct Node*)malloc(sizeof(struct Node));
    struct Node* ptail=newhead;
    while(cur)
    {
        ptail->next=cur;
        ptail=ptail->next;
        if(cur->next)
        cur=cur->next->next;
        else
        cur=NULL;
    }
    return newhead->next;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值