当前位置: 首页 > article >正文

单链表的“影分身术”:随机指针链表的深度拷贝实现

题目如下:

随机链表的复制:

在这里插入图片描述

解题过程如下:

里面的一个括号表示一个结点,包括结点存储的数值val、random指针,这里的random表示下标(从0开始)next指针不用给出来,因为next指针始终指向下一个结点:

在这里插入图片描述

题干提到了深拷贝,有深拷贝就有浅拷贝,那么就来说说什么是深/浅拷贝吧~
浅拷贝也就是值拷贝。例如,(函数的传值调用);还比如,浅拷贝当前的结点,那么两个指针pcurrepeat都指向这个结点:

在这里插入图片描述

深拷贝就是只有地址不一样的两个空间。比如,深拷贝一个结点,那么就要向操作系统申请一个结点大小的空间,两个结点的大小、结点里的数值、next指针一样,只有地址不一样:

在这里插入图片描述

若创建新链表,random指针不好设置,因为random指针要指向链表中的任何结点或空结点。

思路:

  1. 在原链表基础上深拷贝结点并插入在原链表中

在这里插入图片描述

  1. 设置random指针

在这里插入图片描述

  1. 断开新旧链表

在这里插入图片描述

写完代码后,发现会有对空指针的解引用的风险:

在这里插入图片描述
在这里插入图片描述

完整代码如下:

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
typedef struct Node Node;
Node* buyNode(int x)
{
    Node* newnode = (Node*)malloc(sizeof(Node));
    newnode->val = x;
    newnode->next = newnode->random = NULL;
    return newnode;
}
void AddNode(Node* head)
{
    Node* pcur = head;
    while (pcur)
    {
        Node* newnode = buyNode(pcur->val);
        Node* next = pcur->next;
        newnode->next = pcur->next;
        pcur->next = newnode;
        pcur = next;
    }
}
void setRandom(Node* head)
{
    Node* cur = head;
    while (cur)
    {
        Node* copy = cur->next;
        if (cur->random)
            copy->random = cur->random->next;
        cur = copy->next;        
    }
}
struct Node* copyRandomList(struct Node* head) {
    //若链表为空
    if (head == NULL)
    {
        return head;
    }
	//深拷贝原链表中的结点并插入到原链表中
    AddNode(head);
    //设置random指针
    setRandom(head);
    //断开新旧链表
    Node* pcur = head;
    Node* copyHead, *copyTail;
    copyHead = copyTail = pcur->next;
    while (copyTail->next)
    {
        pcur = copyTail->next;
        copyTail->next = pcur->next;
        copyTail = copyTail->next;
    }
    return copyHead;
}

http://www.kler.cn/a/532185.html

相关文章:

  • Baklib探讨如何通过内容中台提升组织敏捷性与市场竞争力
  • 电控---中断
  • C++泛型编程指南09 类模板实现和使用友元
  • 02.04 数据类型
  • DeepSeek-R1:通过强化学习激励大型语言模型(LLMs)的推理能力
  • 【爬虫】JS逆向解决某药的商品价格加密
  • 知识蒸馏教程 Knowledge Distillation Tutorial
  • ES6基础内容
  • [特殊字符] ChatGPT-4与4o大比拼
  • 基于SpringBoot体育商品推荐设计与实现
  • Spring Boot常用注解深度解析:从入门到精通
  • 排序算法与查找算法
  • Blender的材质节点中 透射(Transmission) 和 Alpha的区别
  • Leetcode 3439. Reschedule Meetings for Maximum Free Time I
  • 深度学习 Pytorch 建模可视化工具TensorBoard的安装与使用
  • 关于图像锐化的一份介绍
  • Spring 实现注入的方式
  • 深入解析FastParquet库:高效处理Parquet文件的Python利器
  • 【华为OD-E卷 - 任务最优调度 100分(python、java、c++、js、c)】
  • 【STM32系列】在串口上绘制正弦波
  • 目前市场主流的AI PC对于大模型本地部署的支持情况分析-Deepseek
  • 线程的概念
  • Linux远程登陆
  • PAT甲级1032、sharing
  • 华水967数据结构2024真题(回忆版)
  • chatGPT写的网页版贪吃蛇小游戏