A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
思路:首先copy node, 再copy 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) {
// copy node;
Node cur = head;
HashMap<Node, Node> hashmap = new HashMap<>();
while(cur != null) {
Node newnode = new Node(cur.val);
hashmap.put(cur, newnode);
cur = cur.next;
}
cur = head;
while(cur != null) {
Node curnext = cur.next;
// copy next;
hashmap.get(cur).next = hashmap.get(curnext);
// copy random;
hashmap.get(cur).random = hashmap.get(cur.random);
cur = curnext;
}
return hashmap.get(head);
}
}