思路
1、保存一个原来链表节点与新链表节点之间的映射
2、在创建关系时候,也是通过遍历map来实现
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
Map<Node, Node> map = new HashMap<>();
Node newNode = new Node(0);
Node newHead = newNode;
Node curr = head;
while(head != null){
Node node = new Node(head.val);
node.next = head.next;
node.random = null;
map.put(head, node);
newNode.next = node;
newNode = node;
head = head.next;
}
while(curr!=null){
//得到get:<key>.value2,3
map.get(curr).next = map.get(curr.next); //新结点next指向同旧结点的next指向
map.get(curr).random = map.get(curr.random); //新结点random指向同旧结点的random指向
curr = curr.next;
}
return newHead.next;
}
}