【算法】复制含有随机指针节点的链表

问:

rand指针是单链表节点结构中新增的指针,rand可能指向链表中的任意一个节点,也可能指向null。给定一个由Node节点类型组成的无环单链表的头节点head,请实现一个函数完成这个链表的复制,并返回复制的新链表的头节点

答:

(1) 使用额外空间

初始化一个哈希表,key为Node类型,存储老节点,value也为Node类型,存储克隆的新节点。遍历每一个老节点,生成对应的克隆节点,并把这两个节点的内存地址放入到map中去。然后设置新链表的next方向和random方向的指针,遍历老链表,通过map查出它的新链表,设置上next指针,random指针同理

java 复制代码
//使用额外空间哈希表
public static Node copyListWithRand1(Node head) {
  HashMap<Node, Node> map = new HashMap<Node, Node>();
  Node cur = head;
  while (cur != null) {
    map.put(cur, new Node(cur.value));
    cur = cur.next;
  }
  cur = head;
  while (cur != null) {
    map.get(cur).next = map.get(cur.next);
    map.get(cur).rand = map.get(cur.rand);
    cur = cur.next;
  }
  return map.get(head);
}

(2) 不使用额外空间

首先生成克隆节点,把克隆节点就放在当前老链表节点的下一个,然后把原来老链表的下一个节点放在克隆节点的后面,接着一对一对的拿出老节点和新节点进行处理

java 复制代码
public static Node copyListWithRand2(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;
  }
  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;
  }
  return res;
}
相关推荐
ZJU_统一阿萨姆6 分钟前
【算子开发】Reduction算子完全指南
人工智能·算法·语言模型
鹿角片ljp9 小时前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
鼎艺创新科技9 小时前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
石头猫灯10 小时前
WordPress wp2shell 漏洞链完整拆解流程
网络·数据结构·安全·web安全
.道阻且长.11 小时前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展
wenyq712 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.13 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
青 春 记 忆13 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
小欣加油13 小时前
leetcode3069 将元素分配到两个数组中I
数据结构·c++·算法·leetcode·职场和发展
不会代码的小猴13 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json