47 lines
907 B
Java
47 lines
907 B
Java
/*
|
|
* @lc app=leetcode id=138 lang=java
|
|
*
|
|
* [138] Copy List with Random Pointer
|
|
*/
|
|
|
|
// @lc code=start
|
|
/*
|
|
// Definition for a Node.
|
|
class Node {
|
|
int val;
|
|
Node next;
|
|
Node random;
|
|
|
|
public Node(int val) {
|
|
this.val = val;
|
|
this.next = null;
|
|
this.random = null;
|
|
}
|
|
}
|
|
*/
|
|
|
|
class Solution {
|
|
public Node copyRandomList(Node head) {
|
|
if(head == null) {
|
|
return null;
|
|
}
|
|
Map<Node, Node> ref = new HashMap<>();
|
|
Node cur = head;
|
|
while(cur != null) {
|
|
Node cp = new Node(cur.val);
|
|
ref.put(cur, cp);
|
|
cur = cur.next;
|
|
}
|
|
cur = head;
|
|
while(cur != null) {
|
|
Node nd = ref.get(cur);
|
|
nd.next = ref.get(cur.next);
|
|
nd.random = ref.get(cur.random);
|
|
cur = cur.next;
|
|
}
|
|
return ref.get(head);
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|