码迷,mamicode.com
首页 > 其他好文 > 详细

复制Random链表

时间:2019-10-09 15:32:38      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:ret   random   链表   stat   new   dom   node   ||   ==   

1 空间复杂度O(M)

public static Node copy(Node node){

if(node==null||node.next==null)

 return node;

Node cu=node;

HashMap<Node ,Node> map=new HashMap<>();

while cu!=null){

map.put( cu,new Node( cu.val));

cur=xur.next;}

cur=node;

while( cu!=null){

map.get( cu).next=map.get( cu.next);

map.get( cu).random=map.get( cu.random);

cur=cur.next;

}

return map.get(node);

}

空间复杂度O(1)

public static Node copy(Node node){

if(node==null||node.next==null)

 return node;

Node cu=node;

Node next=null;

//复制链表

while(cu!=null){

next=cur.next;

cur.next=new Node(cur.val);

cur.next.next=next;

cur=next;

}

cur=node;

Node cop=null;

while(cop!=null){

next=cur.next.next;

cop=cur.next;

cop.random=cur.random==null?null:cur.random.next;

cur=next;

}

cur=node;

Node ret=node.next;

while(cop!=null){

next=cur.next.next;

cop=cur.next;

cur.next=next;

cop.next=cur.next==null?null:cur.next.next;

cur=next;

}

return ret;

}

 

复制Random链表

标签:ret   random   链表   stat   new   dom   node   ||   ==   

原文地址:https://www.cnblogs.com/bowenqianngzhibushiwo/p/11641781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!