This commit is contained in:
fanxb 2022-03-08 20:38:07 +08:00
parent 11c5fe7e3f
commit 73748b9dd7

View File

@ -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<Node, Node> 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;
}
}