day16 leetcode-hot100-32(链表11)
138. 随机链表的复制 - 力扣(LeetCode)
1.哈希表
思路
第一次遍历创建新节点并将原节点与新节点同时放入哈希表中
第二次遍历为新节点加入next与random
具体代码
/*
// 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) {HashMap<Node,Node> map = new HashMap<>();Node cur = head;while(cur!=null){map.put(cur,new Node(cur.val));cur=cur.next;}cur=head;while(cur!=null){Node n = map.get(cur);n.next = map.get(cur.next);n.random = map.get(cur.random);cur=cur.next;}return map.get(head);}
}