138. Copy List with Random Pointer - jiejackyzhang/leetcode-note GitHub Wiki
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.
解题思路为采用hash map来存储original node和copy node。 从而copy node的next和random都可以从original node得到。
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null) return null;
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode cur = head;
while(cur != null) {
map.put(cur, new RandomListNode(cur.label));
cur = cur.next;
}
for(Map.Entry<RandomListNode, RandomListNode> entry : map.entrySet()) {
RandomListNode node = entry.getValue();
node.next = map.get(entry.getKey().next);
node.random = map.get(entry.getKey().random);
}
return map.get(head);
}
}