Using hashmap is much easier to implement the code.
O(n) time complexity and O(n) space
First, get the regular linked list and put the node pair in the hashmap
Second, set each node with correct random pointer.
public RandomListNode copyRandomList(RandomListNode head) {
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode p = head;
RandomListNode dummy = new RandomListNode(0);
RandomListNode q = dummy;
while (p!=null) {
q.next = new RandomListNode(p.label);
map.put(p, q.next);
p = p.next;
q = q.next;
}
p = head;
q = dummy;
while (p != null) {
q.next.random = map.get(p.random);
p = p.next;
q = q.next;
}
return dummy.next;
}
Better solution with O(n) time complexity and O(1) space.
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode p = head;
//copy the node in the list
while (p != null) {
RandomListNode next = p.next;
RandomListNode copy = new RandomListNode(p.label);
p.next = copy;
copy.next = next;
p = next;
}
//Set the random pointer correctly
p = head;
while (p != null) {
p.next.random = (p.random != null) ? p.random.next : null;
p = p.next.next;
}
//Reset the list to the original one
p = head;
RandomListNode headCopy = (p!=null) ? p.next : null;
while (p != null) {
RandomListNode copy = p.next;
p.next = copy.next;
p = p.next;
copy.next = (p != null) ? p.next : null;
}
return headCopy;
}
No comments:
Post a Comment