【问题标题】:Copying a linked list node and inserting it in the middle of a linked list复制链表节点并将其插入到链表的中间
【发布时间】: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 时,您并没有复制对象。您只是在提供另一种访问该对象的方法。换句话说,tempcurrent引用同一个对象。

标签: java list methods linked-list


【解决方案1】:

如果您执行了temp = current,您将不会复制该对象。您将只是提供另一种访问该对象的方法。换句话说,tempcurrent引用同一个对象。

如果你这样做了,线条

temp.next = current.next; 
temp.item = current.item;

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

还有,在行中

current.next = temp;

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

【讨论】:

    猜你喜欢
    • 2012-10-27
    • 2016-03-30
    • 2013-02-06
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    相关资源
    最近更新 更多