简体   繁体   English

链接列表(Java)中的逻辑错误插入节点

[英]Logic Error Inserting Node in Linked List (Java)

I am trying to learn to insert a node in a linked list (and return the head), but for some reason it is not correct. 我正在尝试学习在链接列表中插入节点(并返回头),但是由于某些原因,它是不正确的。

This is my approach: 这是我的方法:

1. Create the new node with the desired data 1.使用所需数据创建新节点

2. If we want to insert it in the beginning, point this new node to the head and return the new node 2.如果要在开头插入,请将这个新节点指向头并返回新节点

3. Otherwise, loop to the position where we want to insert the node 3.否则,循环到我们要插入节点的位置

- Once we get there, point the node to be inserted's next to the current node's next -到达目的地后,将要插入的节点指向当前节点的下一个节点

- Point the current node to the node to be inserted -将当前节点指向要插入的节点

- Return the head -返回头

Why does this not work? 为什么这不起作用? Thanks so much! 非常感谢!

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;
}

Given that you insert the new node after the curr node, this loop steps one node too far. 假设您将新节点插入curr节点之后,则此循环将一个节点curr得太远。

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

You can easily work this out by stepping through through the code with a pen and paper, or with a debugger. 您可以使用笔和纸或使用调试器逐步遍历代码,从而轻松解决此问题。

If you insert the node to the Head you need to set the Head to the node you're inserting. 如果将节点插入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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM