138
每个pointer有两个指向,next random,
node1, nod
output 返回deepcopy,
四步完成
1. 检查当前node 是否被拷贝过,如果没有,先拷贝一份当前node 到hash map;
2. 把 copy node 加入到list 中,即 copy next pointer;
3.copy 当前弄得的random pointer
4. 对于original list 每个节点都做以上三个动作。
建立dummy node 这是新建list 的头节点;-不用处理 corner case
public class solution
public RandomListNode copy(RandomListNode head){
if(head==null) return null;
// sentinel node to help construct the deep copy
randdomListNode dummy= new RandomListNode(0);
RandomListNode cur=dummy;
//maintain the mapping between the node in the original lsit and the corresponding node in the new list
Map<randomListNode, RandomListNode> map= new HashMap<>();
while(head!=null){
// copy the node if necessay'
if(!map.containsKey(head)){
map.put(head,new RandomLsitNode(head.value));
}
cur.next=map.get(head);
if(head.random!=null){
if(!map.containsKey(head.random)){
map.put(head.random,new RandomListNode(head.random.value);
//connect the copied node to the deep copy list;
}
cur.next.random=map.get(head.random);
// copy the random node if necesay
}
head=head.next;
cur=cur.next;
}
return dummy.next;
}}
浙公网安备 33010602011771号