求助大家,剑指offer里面的一道题,百思不得其解

求助大家,剑指offer里面的一道题,百思不得其解

这是我的代码:
import java.util.ArrayList;

public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
RandomListNode head=null;
if(pHead==null){

}
else {
ArrayList<RandomListNode> list1=new ArrayList<RandomListNode>();
ArrayList<RandomListNode> list2=new ArrayList<RandomListNode>();
head=new RandomListNode(pHead.label);
list1.add(pHead);
list2.add(head);
//这里将head改成head.next,然后下面的head.next直接用head就不行了。
creatList(list1,list2,pHead.next,head);
getRandomOrder(list1,list2);
head=list2.get(0);
}
return head;
}

void creatList(ArrayList<RandomListNode> list1,ArrayList<RandomListNode> list2,RandomListNode p,RandomListNode head){
if(p==null){
return;
}
else{
//RandomListNode node=new RandomListNode(p.label);
head.next=new RandomListNode(p.label);
//head.next=node;
list1.add(p);
list2.add(head.next);
creatList(list1,list2,p.next,head.next);
}
}

void getRandomOrder(ArrayList<RandomListNode> list1,ArrayList<RandomListNode> list2){
for(int i=0;i<list1.size();i ){
if(list1.get(i).random==null){
continue;
}
for(int j=0;j<list1.size();j ){
if(list1.get(i).random==list1.get(j)){
list2.get(i).random=list2.get(j);
break;
}
}
}
}
}


我知道讨论区有更好的办法,我只是不解我在构造一个新的链表和原来一样时,creatList()方法里面传递的如果是head.next,然后函数里面的head.next改成head就不行了,这是为什么?
#笔试题目#
全部评论
改了的话  head链表就连接不了吧  没有next指向
点赞 回复 分享
发布于 2019-08-08 11:35

相关推荐

04-29 22:35
门头沟学院 Java
牛友说改了名字能收到offer:旧图新发查看图片
点赞 评论 收藏
分享
04-13 11:05
中国海洋大学
ResourceUtilization:两万块的算法专家给HR自己都整笑了
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务