Return a deep copy of the list.
Idea: It can be done recursively or iteratively. In recursive algorithm, use a HashMap<original label, new node> to remember the copied nodes.
In iterative algorithm, use a HashMap<original node, new node> to remember the copied nodes. Iterate through the .next pointer while create an unfinished .random node for later update.
Time: O(n) Space: O(n)
Recursive Code:
public class Solution {
public HashMap<Integer,RandomListNode> copied=new HashMap<Integer,RandomListNode>();
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null)
{
return null;
}
if(copied.containsKey(head.label))
{
return copied.get(head.label);
}
RandomListNode newNode=new RandomListNode(head.label);
copied.put(head.label,newNode);
newNode.next=copyRandomList(head.next);
newNode.random=copyRandomList(head.random);
return newNode;
}
}
Iterative Code: public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null)
{
return null;
}
HashMap<RandomListNode,RandomListNode> copied=new HashMap<RandomListNode,RandomListNode>();
RandomListNode dummy=new RandomListNode(0);
RandomListNode pre=dummy;
while(head!=null)
{
RandomListNode newNode;
if(copied.containsKey(head))
{
newNode=copied.get(head);
}
else
{
newNode=new RandomListNode(head.label);
copied.put(head,newNode);
}
pre.next=newNode;
if(head.random!=null)
{
if(copied.containsKey(head.random))
{
newNode.random=copied.get(head.random);
}
else
{
newNode.random=new RandomListNode(head.random.label);
copied.put(head.random,newNode.random);
}
}
pre=newNode;
head=head.next;
}
return dummy.next;
}
}
No comments:
Post a Comment