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

深拷贝,是指将该链表除了正常单链表的数值和next指针拷贝,再将random指针进行拷贝

想法一

先拷贝出一份链表,再对于每个节点的random指针,在原链表进行遍历,找到random指针的指向,最后完成拷贝链表random的指向
时间复杂度:O(N^2)

想法二

下面这种方法,是使用C语言的最优解

时间复杂度:O(N)

完整代码如下:

cpp 复制代码
struct Node* copyRandomList(struct Node* head)
{
	//1.拷贝节点插入原节点的后面
    struct Node* cur = head;

    while (cur)
    {
        struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        copy->val = cur->val;
        struct Node* next = cur->next;

        copy->next = next;
        cur->next = copy;
        cur = next;
    }
    //2.控制拷贝节点的random
    cur = head;

    while (cur)
    {
        struct Node* copy = cur->next;
        
        if (cur->random)
        {
            copy->random = cur->random->next;
        }
        else
        {
            copy->random = NULL;
        }
        cur = copy->next;
    }
    //3.拷贝节点解下来组成拷贝链表,恢复原链表
    cur = head;
    struct Node* copyHead = NULL;
    struct Node* copyTail = NULL;

    while (cur)
    {
        struct Node* copy = cur->next;
        struct Node* next = copy->next;

        if (copyTail)
        {
            copyTail->next = copy;
            copyTail = copyTail->next;
        }
        else
        {
            copyHead = copyTail = copy;
        }

        cur->next = next;
        cur = next;
    }

    return copyHead;
}
相关推荐
第七序章35 分钟前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
仙俊红35 分钟前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
l1t3 小时前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb
l1t4 小时前
利用美团龙猫用libxml2编写XML转CSV文件C程序
xml·c语言·libxml2·解析器
散11210 小时前
01数据结构-01背包问题
数据结构
消失的旧时光-194310 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww10 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长11 小时前
C语言---循环结构
c语言·开发语言·算法
苏小瀚12 小时前
[数据结构] 排序
数据结构
程序猿编码12 小时前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备