/*
// 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) {
Node cur = new Node(0);
cur = head;
Map<Node,Node> nodeMap = new HashMap<>();
while(cur!=null){
Node newNode = new Node(cur.val);
nodeMap.put(cur,newNode);
cur = cur.next;
}
cur = head;
while(cur!=null){
nodeMap.get(cur).next = nodeMap.get(cur.next);
nodeMap.get(cur).random = nodeMap.get(cur.random);
cur = cur.next;
}
return nodeMap.get(head);
}
}
题解:
- 两次遍历链表,第一次遍历用哈希表存储节点,key为旧节点,value为新节点,此次遍历只存val。
- 第二次遍历,取出新节点,让新节点的next指针指向旧next节点对应的value(新节点),让新节点的random指针指向旧random节点对应的value(新节点)。