题目描述
知识点:
1.哈希表 哈希表的相关知识点_jcxj2934的博客-CSDN博客
2.链表的相关知识: 剑指 Offer 06. 从尾到头打印链表_jcxj2934的博客-CSDN博客
思路及代码如下:
写法参考了leetcode的官方答案
/*
// 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 {
HashMap<Node,Node> map = new HashMap<>();
public Node copyRandomList(Node head) {
//先通过next将新链表创建一遍<1>
//创建好后再给random赋值
//做random的时候可以通过hash表来快速找到旧节点对应的新节点
//key 是旧的链表节点,value是新的链表节点
if(head == null)
{
return null;
}
//如果节点不存在,就创建<1>
//在next遍历的时候都是不存在的,所以这一个if是先通过next将新链表都创建一遍
if(!map.containsKey(head))
{
Node headnew = new Node(head.val);
map.put(head,headnew);
headnew.next = copyRandomList(head.next);
headnew.random = copyRandomList(head.random);
}
//为random赋值时才会走到这里,返回新的节点
return map.get(head);
}
}