- /*
- // 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;
- }
- Node cur = head;
- HashMap
map = new HashMap<>(); - while(cur != null) {
- //存放的是旧节点对应的新节点
- map.put(cur,new Node(cur.val));
- cur = cur.next;
- }
- //再次遍历老链表
- cur = head;
- while(cur != null) {
- //取出map中的值,也就是新的节点,进行拷贝连接
- map.get(cur).next = map.get(cur.next);
- map.get(cur).random = map.get(cur.random);
- cur = cur.next;
- }
- //返回老结构对应的头,就是新结构对应的头节点
- return map.get(head);
- }
- }