Copy List with Random Pointer
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.
My Answer
/**
* 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;
}
RandomListNode pivot = head;
int total = 0;
while(pivot != null){
total++;
pivot = pivot.next;
}
RandomListNode[] array = new RandomListNode[total];
pivot = head;
array[0] = new RandomListNode(pivot.label);
array[0].next = null;
array[0].random = pivot.random;
pivot = pivot.next;
for(int i = 1; i < total; i++){
array[i] = new RandomListNode(pivot.label);
array[i - 1].next = array[i];
array[i].next = null;
array[i].random = pivot.random;
pivot = pivot.next;
}
Map<RandomListNode,Integer> map = new HashMap<RandomListNode,Integer>();
pivot = head;
int index = 0;
while(pivot != null){
map.put(pivot,index);
pivot = pivot.next;
index++;
}
pivot = head;
for(int i = 0; i < total; i++){
if(pivot.random != null){
array[i].random = array[map.get(pivot.random)];
}
pivot = pivot.next;
}
return array[0];
}
}