我正在编写一个名为 twin() 的方法,它将采用链表 [1 2 3 4] 并返回 [1 1 2 2 3 3 4 4]。我有一个工作方法,但我对一部分感到困惑。在我的代码中,我声明了一个名为 temp 的新 SListNode 变量。我希望这个临时节点复制当前节点然后连接它。当我尝试执行 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;
}
}
最佳答案
如果您执行了temp = current
,则不会复制该对象。您将只是提供另一种访问该对象的方法。换句话说,temp
和 current
将引用同一个对象。
如果你这样做了,这些行
temp.next = current.next;
temp.item = current.item;
不会做任何事情,因为它就像做temp.next = temp.next
。
另外,在行中
current.next = temp;
您将使 current
的下一个节点成为其自身(current.next
将是 current
)。
关于java - 复制链表节点并将其插入到链表中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24104998/