【发布时间】:2014-06-08 10:01:53
【问题描述】:
我正在编写一个名为 twin() 的方法,它将采用链表 [1 2 3 4] 并返回 [1 1 2 2 3 3 4 4]。我有一个工作方法,但我对一部分感到困惑。在我的代码中,我声明了一个名为 temp 的新 SListNode 变量。我希望这个 temp 复制当前节点,然后连接它。当我尝试执行 SListNode temp = current 时,程序将无法运行。但是,如果我手动设置 temp 的 item 和 next 字段,该方法将运行得很好。谁能解释一下当您执行 SListNode temp = current 时会发生什么?
public void twin() {
SListNode current = head;
if(current == null){
return;
}
for(int i = 0; i <this.length();i++){
if(current == null){
return;
}
SListNode temp = new SListNode(0); // Problem here when I substitute these 3 lines for SListNode temp = current;
temp.next = current.next;
temp.item = current.item;
current.next = temp;
current = current.next.next;
}
}
【问题讨论】:
-
“程序无法运行”是什么意思。你遇到了什么错误?
-
是循环列表吗? length() 是如何计算的?
-
请注意,当您执行
temp = current时,您并没有复制对象。您只是在提供另一种访问该对象的方法。换句话说,temp和current将引用同一个对象。
标签: java list methods linked-list