/*
// 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> map = new HashMap<>();
Node temp = head;
//创建一个与当前节点对应的节点放进map里面去
while(temp != null) {
map.put(temp, new Node(temp.val));
temp = temp.next;
}
Node target = map.get(head);
Node p = target;
while(head != null) {
target.next = map.get(head.next);
target.random = map.get(head.random);
target = target.next;
head = head.next;
}
return p;
}
}
算法-哈希表-复制带随机指针的链表
最新推荐文章于 2023-02-10 16:33:51 发布