From 73748b9dd7d991fbda950bb62c0b0183edf60b5a Mon Sep 17 00:00:00 2001 From: fanxb Date: Tue, 8 Mar 2022 20:38:07 +0800 Subject: [PATCH] add --- 5.leetcode/src/com/fanxb/common/Q138.java | 46 +++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 5.leetcode/src/com/fanxb/common/Q138.java diff --git a/5.leetcode/src/com/fanxb/common/Q138.java b/5.leetcode/src/com/fanxb/common/Q138.java new file mode 100644 index 0000000..947f82c --- /dev/null +++ b/5.leetcode/src/com/fanxb/common/Q138.java @@ -0,0 +1,46 @@ +package com.fanxb.common; + +import java.util.HashMap; +import java.util.Map; + +/** + * TODO + * + * @author FleyX + * @date 2022/3/3 22:35 + */ +public class Q138 { + private static class Node { + int val; + Node next; + Node random; + + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; + } + } + + public Node copyRandomList(Node head) { + //老节点和新节点的对应关系 + Map oldNewMap = new HashMap<>(); + //建立虚拟头节点便于处理 + Node res = new Node(0), tempNew = res, tempOld = head; + while (tempOld != null) { + tempNew.next = new Node(tempOld.val); + tempNew = tempNew.next; + //旧节点和新节点一一对应 + oldNewMap.put(tempOld, tempNew); + tempOld = tempOld.next; + } + //再次便利将random关系处理好 + while (head != null) { + if (head.random != null) { + oldNewMap.get(head).random = oldNewMap.get(head.random); + } + head = head.next; + } + return res.next; + } +}