题目
复制带 next 和 random 指针的链表。每个输入元素是 [值, random 指向的下标],null 表示空指针。新链表所有节点必须与原链表不同。
示例输入
head = [[7,null],[13,0],[11,4],[10,2],[1,0]]示例输出
[[7,null],[13,0],[11,4],[10,2],[1,0]]思路
第一遍为每个原节点创建新节点,并记录原节点到副本的映射。第二遍通过映射复制 next、random 两种连接。
每一步都成立
连接副本之前,每个原节点都已经有唯一副本;副本的指针只指向副本节点。
看它一步步执行
用的是题目示例按平常的写法填:数组写 2 7 11 15 或 2, 7, 11, 15,矩阵每行一行,字符串不用加引号。也可以把力扣的示例整行粘贴进来,例如 nums = [2,7,11,15], target = 9。
核对结果(可选)
数组 / nums步骤 1
执行状态
这次的结果
播放到最后查看Solution.java参考解法 · 高亮的是正在执行的行
1class Solution {2 public Node copyRandomList(Node head) {3 Map<Node, Node> copies = new HashMap<>();4 for (Node current = head; current != null; current = current.next) {5 copies.put(current, new Node(current.val));6 }7 for (Node current = head; current != null; current = current.next) {8 Node copy = copies.get(current);9 copy.next = copies.get(current.next);10 copy.random = copies.get(current.random);11 }12 return copies.get(head);13 }14}
← → 单步 · 空格 播放
自己写一遍
只需实现下面的方法,输入输出由判题机处理。运行用下方的测试用例试一试;提交再用约 10 组隐藏用例检验。草稿自动保存在这个浏览器里。
还没有运行。写好代码后点“运行”。
ListNode、TreeNode、Node 已经定义好,可以直接使用;java.util 已默认导入。单组输入最多运行 4 秒,提交最多 6 秒。服务器同一时间只运行一份代码,人多时可能要排队几秒。