/**
* 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;
}
// Copies node after the original node
for(RandomListNode itr = head; itr != null; ) {
RandomListNode copy = new RandomListNode(itr.label);
copy.next = itr.next;
itr.next = copy;
itr = copy.next;
}
// Copies random pointers
for(RandomListNode itr = head; itr != null; itr = itr.next.next) {
itr.next.random = itr.random == null ? null : itr.random.next;
}
// Splits two lists
RandomListNode copyOfHead = head.next;
for(RandomListNode itr = head, copyItr = copyOfHead; itr != null; itr = itr.next, copyItr = copyItr.next) {
itr.next = itr.next.next;
copyItr.next = copyItr.next == null ? null : copyItr.next.next;
}
return copyOfHead;
}
}
Time: O(n)
Space: O(n)