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;
}
相关推荐
qq_513970444 小时前
力扣 hot100 Day56
算法·leetcode
爱装代码的小瓶子6 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男7 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao7 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
快乐飒男8 小时前
哈希表(c语言)
c语言·哈希算法·散列表
aramae9 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
大锦终9 小时前
【算法】前缀和经典例题
算法·leetcode
cccc来财10 小时前
Java实现大根堆与小根堆详解
数据结构·算法·leetcode
程序员编程指南11 小时前
Qt 数据库连接池实现与管理
c语言·数据库·c++·qt·oracle
恣艺11 小时前
LeetCode 854:相似度为 K 的字符串
android·算法·leetcode