138. Copy List with Random Pointer
Medium
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.
/**
* 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 (null == head) {
return head;
}
RandomListNode pNode = head;
RandomListNode preNode = new RandomListNode(0);
RandomListNode ptr = preNode;
Map<RandomListNode, RandomListNode> mrr = new HashMap<>();
while (pNode != null) {
RandomListNode tNode = new RandomListNode(pNode.label);
mrr.put(pNode, tNode);
ptr.next = tNode;
ptr = tNode;
}
pNode = head;
ptr = preNode.next;
while (pNode != null) {
ptr.random = mrr.get(pNode.random);
pNode = pNode.next;
}
return preNode.next;
}
}