【leetcode】138. 随机链表的复制

该文章介绍了如何在LeetCode题目中实现随机链表的高效复制,通过三个步骤创建新链表副本并保持原链表的random指针关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode题目链接 138. 随机链表的复制
在这里插入图片描述

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
typedef struct Node Node;
Node* copyRandomList(Node* head) {
    if (head != NULL) {
        // 1.在cur后面copy一份cur
        for (Node* cur = head; cur != NULL; cur=cur->next->next) {
            Node* newnode = (Node*)malloc(sizeof(Node));
            newnode->val = cur->val;
            newnode->next = cur->next;
            cur->next = newnode;
        }
        // 2.将每个copy的节点的random指针补充完整
        for (Node* cur = head; cur != NULL; cur=cur->next->next) {
            Node* newnode = cur->next;
            newnode->random = cur->random ? cur->random->next : NULL;
        }
        // 3.将copy的节点依次取下
        Node* newhead = head->next;
        for (Node* cur = head; cur != NULL; cur = cur->next) {
            Node* newnode = cur->next;
            cur->next = cur->next->next;
            newnode->next = newnode->next ? newnode->next->next : NULL;
        }
        return newhead;
    }
    return NULL;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

念来过倒字名qwq

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

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

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

打赏作者

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

抵扣说明:

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

余额充值