【问题标题】:Linked list - Can't figure out why this insert before method is causing the link list to expand链接列表 - 无法弄清楚为什么这个 insert before 方法会导致链接列表扩展
【发布时间】:2013-11-30 04:09:34
【问题描述】:

当我不使用“insertBefore”方法时,它只是正常打印出链表,就像它应该做的那样。但是当我尝试使用 insertBefore 方法时,它确实适用于第一部分,但它会继续打印链接列表,就好像它永远持续下去一样,

例如:

在打印出之前没有插入“我的测试::::
头 -> 3 -> 2 -> 1 -> 4 -> ||| "

但是当我使用 insertBefore 并打印出来时,它会打印出来

头部 ->3 -> 4 -> 2 -> 1 -> 4 -> 2 -> 1 -> 4 -> 2 -> 1 -> 4 -> 2 -> 1 -> 4 -> 2 - > 1 -> 4 -> 它会一直持续下去

这里是 insertBefore 方法

private boolean insertBefore(Node aNode, Node beforeNode)
{
    Node currentNode;
    Node prevNode;
    //aNode= new Node();

    currentNode = this.getHead();

    while(currentNode!=null && currentNode.getNext()!=aNode)
    {

        if(currentNode == beforeNode)
            {
                prevNode = this.getPrevious(beforeNode);
                prevNode.setNext(aNode);
                aNode.setNext(beforeNode);
                //aNode.setNext(currentNode);
                return true;
            }

        currentNode = currentNode.getNext();
    }
    currentNode.setNext(beforeNode);

    return false;

}

insertBefore 方法确实完成了它的工作,但是它使链接列表永远继续存在,我想知道为什么

【问题讨论】:

  • 我没有看到你在任何地方更新currentNode 中的上一个节点链接,也没有看到你更新aNode 中的下一个节点链接。

标签: java function methods linked-list


【解决方案1】:

你正在操作一个看起来像双向链表的东西(因为你有 getPrevious)

您当前的列表是: 1 2 3 4

您想在 3 之前添加“a”:

  • 所以你需要找到节点 2 & 3
  • 更新 2.Next 到 a,和 a.Previous 到 2
  • 更新 a.Next 到 3 和 3.Previous 到 a

    我在这里看不到所有这些更新。只有 PrevNode.setNext(aNode)。

    注意(这不是一个双向链表,那么您只缺少 1 组而不是 3 组,但实际上没有必要为了找到前一个节点而对列表进行两次完整的第二次扫描)。

  • 【讨论】:

    • 我不认为它一定是一个双向链表——getPrevious 是在 LL 类本身上定义的,而不是在 Node.js 上定义的。但如果没有来源,我们就无法确定。
    【解决方案2】:

    您需要添加aNode.setNext(currentNode)

    【讨论】:

    • 更多细节将有助于这个答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2015-04-28
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多