Java 复制链表节点并将其插入链表中间

Java 复制链表节点并将其插入链表中间,java,list,methods,linked-list,Java,List,Methods,Linked List,我正在编写一个名为twin()的方法,它将获取一个链表[1234]并返回[1234]。我有一个工作方法,但我对一个部分感到困惑。在我的代码中,我声明了一个名为temp的新SListNode变量。我希望此临时文件复制当前节点,然后连接它。当我尝试执行SListNode temp=current时,程序将不会运行。但是,如果我手动设置temp的item和next字段,该方法将正常运行。有人能解释一下当你使用SListNode temp=current时会发生什么吗 public void twin(

我正在编写一个名为twin()的方法,它将获取一个链表[1234]并返回[1234]。我有一个工作方法,但我对一个部分感到困惑。在我的代码中,我声明了一个名为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;
    }
}
public void twin(){
滑动节点电流=磁头;
如果(当前==null){
返回;
}

对于(int i=0;i如果您执行了
temp=current
,则不会复制该对象。您将只是提供另一种访问该对象的方式。换句话说,
temp
current
将引用同一对象

如果你那样做了,台词

temp.next = current.next; 
temp.item = current.item;
不会做任何事情,因为这就像做
temp.next=temp.next

还有,排队

current.next = temp;

您将使
current
的下一个节点成为自身(
current。next
将是
current
)。

您所说的“程序将不运行”是什么意思。您得到了什么错误?是循环列表吗?长度()计算?请注意,当您执行
temp=current
时,您并不是在复制该对象。您只是提供了访问该对象的另一种方式。换句话说,
temp
current
将引用同一对象。