复制复杂链表@Leetcode —— 单链表

1. 题目

题目链接:复制带随机指针的链表
在这里插入图片描述

2. 思路

这道题目的难点在于 :random指针也都应指向复制链表中的新节点

这思路也太妙了吧!
⭐️ 1. 复制节点,插入在原节点和下一个节点之间
在这里插入图片描述

⭐️ 2. 根据原节点的random,处理复制节点的random
⭐️ 3. 把复制节点解下来,链接成一个新链表,恢复原链表的链接关系。

3. 题解

struct Node* copyRandomList(struct Node* head) {
    if(head == NULL)
        return NULL;
	// 1.复制节点,插入到原节点和下一个节点之间
    struct Node* cur = head;
    while(cur)
    {
        struct Node* copynode = (struct Node*)malloc(sizeof(struct Node));
        copynode->val = cur->val;

        struct Node* next = cur->next;
        //链接
        cur->next = copynode;
        copynode->next = next;
        cur = next;
    }
    // 2. 根据源节点的random处理复制节点的random
    cur = head;
    while(cur)
    {
        if(cur->random == NULL)
        {
            cur->next->random = NULL;
        }
        else
        {
            cur->next->random = cur->random->next;
        }
        cur = cur->next->next;
    }
    // 3.复制节点解下来缝合成新链表,缝合原链表链接关系
    cur = head;
    struct Node* copyhead = head->next;
    while(cur)
    {
        struct Node* copynode = cur->next;
        struct Node* next = copynode->next;
        cur->next = next; //缝合
        //链接
        if(next == NULL) 
            copynode->next = NULL;
        else
            copynode->next = next->next;

        // 迭代
        cur = next;
    }
    return copyhead;
}

这是另一份参考代码,差别主要是在第三部分,它采取尾插构建新链表,我直接在2的结构上缝合。

struct Node* copyRandomList(struct Node* head) {
	struct Node* cur = head;

    //1.拷贝节点,插入到原节点的后面
    while(cur)
    {
        struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        copy->val = cur->val;
        //插入copy节点
        copy->next = cur->next;
        cur->next = copy;
        //迭代着向后走
        cur = copy->next;
    }
    //2.根据原节点,处理copy节点的random
    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;
    }
    //3.把拷贝节点解下来,链接成新链表(尾插链接),同时恢复原链表
    struct Node *copyHead = NULL,*copyTail = NULL;//不需要每次都找尾
    cur = head;
    while(cur)
    {
        struct Node* copy = cur->next;
        struct Node* next = copy->next;
        if(copyTail == NULL)
        {
            //第一个
            copyHead = copyTail = copy;
        }
        else
        {
            //尾插
            copyTail->next = copy;
            copyTail = copy;//这样的话更新
        }
        //恢复原链表
        cur->next = next;

        cur = next;
    }
    return copyHead;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮光 掠影

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值