力扣HOT100之链表:138. 随机链表的复制

这道题要求将整个链表进行深拷贝,新链表中不包含任何原链表的节点,但是新链表中各个节点存储的值和各个节点的指向关系需要和原链表一模一样。我的思考过程如下:

1.新链表中的每一个节点的创建必须用new关键字来创建,而不能只是简单的拷贝赋值;

2.由于ramdom指针的随机性,A -> random可能指向nullptr,也可能指向A之后的某个节点,也有可能指向A之前的某个节点,也有可能指向自己,在构造链表的过程中,完全有可能出现A -> random对应的节点还没构造出来的情况,此外,按照random指针遍历链表可能出现有环的情况,从而导致无限循环。

3.要想遍历链表的所有节点,只能通过next指针进行遍历,因此在构造链表的过程中,我们应当使用next指针遍历整个链表,先将新链表的所有节点构造出来,然后再来逐个处理每一个节点的random指针的指向问题。
还有一个问题,就是原链表中的节点Arandom指针指向节点B,我们怎么将新链表中A'random指针指向B'?

我们可以使用一个整形变量offset来记录原链表中A -> random指针指向节点(B节点)相较于头节点的偏移量,然后我们在新链表中通过这个偏移量找到对应的节点,再将当前遍历到的节点的random指针指向偏移量为offset的节点。

下面结合一个简单的例子来说明一下解决的过程

代码如下

cpp 复制代码
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        Node* new_head = head ? new Node(head -> val) : nullptr;   //新链表的头节点
        Node* current1 = head;
        Node* current2 = new_head;
        //先根据next指针将所有节点构造出来,并顺序连接
        while(current1){
            current2 -> val = current1 -> val;
            current2 -> next = current1 -> next ? new Node(current1 -> next -> val) : nullptr;
            current1 = current1 -> next;
            current2 = current2 -> next;
        }
        //按照顺序逐一构造random的指向
        current1 = head;
        current2 = new_head;
        while(current1){
            if(current1 -> random){   //random指向链表中的节点
                Node* temp_current1 = head;  //
                int offset = 0;   //计算偏移量
                while(temp_current1 != current1 -> random){
                    ++offset;
                    temp_current1 = temp_current1 -> next;
                }
                Node* temp_current2 = new_head;
                while(offset > 0){  //寻找新链表中当前节点的random指向的位置
                    temp_current2 = temp_current2 -> next;
                    --offset;
                }
                current2 -> random = temp_current2;    
            }
            current1 = current1 -> next;
            current2 = current2 -> next;
        }
        return new_head;
    }
};
相关推荐
Coovally AI模型快速验证5 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·yolo·计算机视觉·transformer·无人机
pusue_the_sun5 小时前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
RaymondZhao346 小时前
【全面推导】策略梯度算法:公式、偏差方差与进化
人工智能·深度学习·算法·机器学习·chatgpt
zhangfeng11336 小时前
DBSCAN算法详解和参数优化,基于密度的空间聚类算法,特别擅长处理不规则形状的聚类和噪声数据
算法·机器学习·聚类
圣保罗的大教堂7 小时前
leetcode 2348. 全 0 子数组的数目 中等
leetcode
啊阿狸不会拉杆7 小时前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
小学生的信奥之路7 小时前
洛谷P3817题解:贪心算法解决糖果分配问题
c++·算法·贪心算法
你知道网上冲浪吗8 小时前
【原创理论】Stochastic Coupled Dyadic System (SCDS):一个用于两性关系动力学建模的随机耦合系统框架
python·算法·数学建模·数值分析
地平线开发者9 小时前
征程 6 | PTQ 精度调优辅助代码,总有你用得上的
算法·自动驾驶
Tisfy10 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率