【问题标题】:Logic Error Inserting Node in Linked List (Java)在链表中插入节点的逻辑错误 (Java)
【发布时间】:2017-02-26 02:34:43
【问题描述】:

我正在尝试学习在链表中插入一个节点(并返回头部),但由于某种原因它不正确。

这是我的方法:

1.使用所需数据创建新节点

2.如果我们要在开头插入,将这个新节点指向头部,返回新节点

3.否则,循环到我们要插入节点的位置

-一旦我们到达那里,将要插入的节点指向当前节点的下一个节点

-将当前节点指向要插入的节点

-回首

为什么这不起作用?非常感谢!

Node InsertNth(Node head, int data, int position) {
    Node node = new Node();
    node.data = data;

    if (position == 0) {
        node.next = head;
        return node;
    }
    else {
        Node curr = head;
        int currPos = 0;

        while (currPos < position) {
            curr = curr.next;
            currPos++;
        }
        node.next = curr.next;
        curr.next = node;
    }
    return head;
}

【问题讨论】:

  • 你的意思是不起作用?到底发生了什么?请说明您的问题;不要让我们阅读代码来弄清楚。
  • 高级代码看起来不错,请告诉我们您遇到的问题。
  • 另外,调用是什么样的;是head = insert(...);吗?
  • 如果你的数据结构中有一个指向 head 的指针,你必须更新它。

标签: java linked-list


【解决方案1】:

鉴于您在 curr 节点之后插入新节点,此循环将一步过长一个节点。

while (currPos < position) {
     curr = curr.next;
     currPos++;
}

您可以通过使用笔和纸或调试器逐步执行代码来轻松解决此问题。

【讨论】:

    【解决方案2】:

    如果将节点插入到 Head 中,则需要将 Head 设置为要插入的节点。

    Node InsertNth(Node head, int data, int position) {
    Node node = new Node();
    node.data = data;
    
    if (position == 0) {
        node.next = head;
        head = node;
    }
    else {
        Node curr = head;
        int currPos = 0;
    
        while (currPos < position) {
            curr = curr.next;
            currPos++;
        }
        node.next = curr.next;
        curr.next = node;
    }
    return head;
    

    }

    【讨论】:

    • 按照共享的算法,返回head。这已在 if 循环中完成。
    • 如果将节点作为头部插入,它会在方法的末尾返回头部,指向插入的节点,因为在 if 循环中我们执行head = node;
    • if循环里面有return语句。它不会结束该方法。 if (position == 0) { node.next = head;返回节点; }
    • 您不需要在if (position == 0) 中使用return head;,因为您总是返回头部。这是多余的。不同之处在于,如果位置为 0,则返回新节点作为头部,如果位置不为 0,则返回相同的头部。
    猜你喜欢
    • 2022-11-20
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 2023-03-24
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多