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.
/**
* 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) {
RandomListNode dummy = new RandomListNode(0);
RandomListNode p = dummy;
RandomListNode curNode = head;
while (curNode != null) {
p.next = clone(curNode);
curNode = curNode.next;
p = p.next;
}
return dummy.next;
}
public RandomListNode clone(RandomListNode node) {
RandomListNode newNode = new RandomListNode(node.label);
if (node.random != null) {
newNode.random = new RandomListNode(node.random.label);
}
return newNode;
}
}
3. Time & Space Complexity