求助大家,剑指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);
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(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就不行了,这是为什么?
#笔试题目#