【算法】复制有随机指针的单链表
左程云算法与数据结构课 https://www.bilibili.com/video/BV13g41157hK?p=2&spm_id_from=pageDriver
题目
一种特殊的单链表节点描述如下
class Node {
int value;
Node next;
Node rand;
Node(int val) {
value = val;
}
}
rand 指针是单链表节点结构中新增的指针,rand 可能指向链表中的任意一个位置,也可能指向 null。给定一个由 Node 节点类型组成的无环单链表的头节点 head,请实现一个函数完成链表的复制,并返回复制的新链表的头节点。要求时间复杂度O(N),空间复杂度O(1)。
题解
设原链表如下
生成克隆节点并放在原节点的下一个位置。
一对一对地把节点拿出来把 rand 指针复制。例如把 1 和 1’ 节点拿出来,1 的 rand 指向 3,故 1‘ 的 rand 指向 3 的下一个节点,即 3’ 节点。
最后分裂成新老链表即可。
public class CopyListWithRandom {
static class Node {
int value;
Node next;
Node rand;
Node(int val) {
value = val;
}
}
public static Node copyListWithRand(Node head) {
if (head == null) {
return null;
}
Node cur = head;
Node next = null;
//复制新节点放在老节点后面
while (cur != null) {
next = cur.next;
cur.next = new Node(cur.value);
cur.next.next = next;
cur = next;
}
//设置复制节点的 rand 指针
cur = head;
Node curCopy = null;
while (cur != null) {
next = cur.next.next;
curCopy = cur.next;
curCopy.rand = cur.rand != null ? cur.rand.next : null;
cur = next;
}
//分裂成新老链表
Node res = head.next;
cur = head;
while (cur != null) {
next = cur.next.next;
curCopy = cur.next;
cur.next = next;
curCopy.next = next != null ? next.next : null;
cur = next;
}
return res;
}
}
本文来自博客园,作者:hzyuan,转载请注明原文链接:https://www.cnblogs.com/hzyuan/p/15820668.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)