010、随机链表复制

0、题目描述

随机链表复制

1、法1

我的第一个想法是,直接把random指针看成一个结构体成员,我创建节点的时候加一个结构体成员不就可以了吗?指针不也是一个地址数据吗?

实际上指针是具有结构特点的,如果按照我的想法复制,random是空的时候没问题,不是空的时候random指针不是指向新链表里面的结构,还是指向原来链表的结构,这条路走不通。

copy链表和原链表得先建立联系,把每一个节点复制在原节点的后面,这样的好处是:
copy链表的random,等于原链表的random的next。 如图。

复制完copy里面的random之后,再把copy链表给解下来,还原原链表。

1、拷贝到每个节点的后面,组成两倍长度的新链表

2、复制里面的random

3、解开copy链表

c 复制代码
/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */

struct Node* BuyNewNode(int val)
{
    struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
    newnode->val = val;
    newnode->next = NULL;
    newnode->random = NULL;
    return newnode;
}

struct Node* copyRandomList(struct Node* head) 
{
    if (head == NULL)
        return NULL;
	struct Node* cur = head;
    struct Node* newnode = NULL;
    struct Node* next = NULL;
    //把每个节点放在原节点的后面
    while (cur)
    {
        next = cur->next;
        newnode  = BuyNewNode(cur->val);
        cur->next = newnode;
        newnode->next = next;
        cur = next;
    }
    
    cur = head;
    struct Node* newlist = cur->next;
    struct Node* newcur = newlist;
    while (cur)
    {
        //复制节点的random,上一个节点random的next
        if (cur->random == NULL)
        {
            newcur->random = NULL;
        } 
        else
        {
            newcur->random = cur->random->next;
        }
        
        //复制完random之前不能动cur->next
        
        cur = cur->next->next;
        if (cur)
            newcur = newcur->next->next;
    }

    //解开
    cur = head;
    newcur = newlist = cur->next;
    while (cur)
    {
        cur->next = newcur->next;
        cur = cur->next;
        if (cur)
        {
            newcur->next = cur->next;
            newcur = newcur->next;
        }
    }
    return newlist;
}

这里注意newcur可能会越界,所以要 if 拦截一下,cur走到头的时候,不要让newcur再走了!

相关推荐
草莓熊Lotso4 分钟前
【数据结构初阶】--二叉树(五)
c语言·数据结构·经验分享·笔记·其他
蒟蒻小袁1 小时前
力扣面试150题--只出现一次的数字
数据结构·算法·leetcode
啊阿狸不会拉杆1 小时前
《Java 程序设计》第 11 章 - 泛型与集合
java·开发语言·jvm·数据结构·算法
Jay Kay3 小时前
跳跃表可视化深度解析:动态演示数据结构核心原理
数据结构·数据库
OKkankan4 小时前
string类的模拟实现
开发语言·数据结构·c++·算法
云手机掌柜6 小时前
从0到500账号管理:亚矩阵云手机多开组队与虚拟定位实战指南
数据结构·线性代数·网络安全·容器·智能手机·矩阵·云计算
没书读了9 小时前
考研复习-数据结构-第八章-排序
数据结构
waveee12310 小时前
学习嵌入式的第三十四天-数据结构-(2025.7.29)数据库
数据结构·数据库·学习
jie*11 小时前
小杰数据结构(one day)——心若安,便是晴天;心若乱,便是阴天。
数据结构
伍哥的传说12 小时前
React & Immer 不可变数据结构的处理
前端·数据结构·react.js·proxy·immutable·immer·redux reducers