Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试复制Java链接列表…我做错了什么?_Java_List_Loops_Linked List_Copy - Fatal编程技术网

尝试复制Java链接列表…我做错了什么?

尝试复制Java链接列表…我做错了什么?,java,list,loops,linked-list,copy,Java,List,Loops,Linked List,Copy,所以我想单独列出一个列表,这样就不会通过我的方法参数来操纵输入的列表。基本上,当循环结束时,我希望“result”与“p”相同……但由于某些原因,它的输出不正确 private static Node<Integer> multByScalarAndCarry(Node<Integer> p , int k, int c){ int carry = c; //carry is taken from parameter Node<

所以我想单独列出一个列表,这样就不会通过我的方法参数来操纵输入的列表。基本上,当循环结束时,我希望“result”与“p”相同……但由于某些原因,它的输出不正确

private static Node<Integer> multByScalarAndCarry(Node<Integer> p , int k, int c){
          int carry = c; //carry is taken from parameter
          Node<Integer> result = new Node<Integer>();
          Node<Integer> z = result; //head for the copy list
          Node<Integer> P = p; //pointer for the list being copied
          //copy p into result
          while(P.next!=null){
              z.item = P.item;
              z.next = new Node<Integer>();
              z = z.next;
              P = P.next;
          }
...
}
私有静态节点multByScalarAndCarry(节点p、int k、int c){
int carry=c;//进位取自参数
节点结果=新节点();
Node z=result;//指向复制列表
节点P=P;//正在复制的列表的指针
//将p复制到结果中
while(P.next!=null){
z、 项目=P.项目;
z、 next=新节点();
z=z.next;
P=P.next;
}
...
}
忽略k和c,它们与我的问题无关。我是如此接近完成这个方法,这是最后一件我需要的。请帮忙

编辑[解决方案]: 对于那些将来有这个问题的人,我使用一种复制列表的单独方法做了一些思考

下面是一个递归解决方案:

private static Node<Integer> copyNode(Node<Integer> p){
       if(p == null) //if empty, return the same thing
           return p;
       Node<Integer> result = new Node<Integer>();
       result.item = p.item;// construct a node item copy of p's item
       result.next = copyNode(p.next); //attach list doing this for all nodes of p
       return result; //return the result.
}
私有静态节点copyNode(节点p){
if(p==null)//如果为空,则返回相同的内容
返回p;
节点结果=新节点();
result.item=p.item;//构造p的项的节点项副本
result.next=copyNode(p.next);//为p的所有节点执行此操作的附加列表
return result;//返回结果。
}

z=z。接下来是问题。您正在将当前节点更改为前一行中的节点。

还不够?更具体地说,“不正确”是什么意思?“不正确”意味着一切都是一样的,只是出于某种原因,最后一个节点的值不为null(项为null,下一个为null,但不为null)。这个节点是从零开始制作的,我们应该从零开始做所有类似的事情。抱歉,英语不好。最后一个节点不是空的,因为您将其实例化为新的
节点
,然后在p为空时中断循环,如果在循环结束后简单地添加
z=null
,它将正确复制。