2016-10-17 129 views
1

我试图学习在链表中插入一个节点(并返回头部),但由于某种原因它不正确。逻辑错误在链接列表(Java)中插入节点

这是我的方法:

1.创建所需的数据

2.新节点。如果我们想将它插入开始的时候,这点新节点的头并返回新节点

否则,环路的地方,我们要插入节点的位置

-一旦到了那儿,指向节点要插入的下一个当前节点的下一个

-点当前节点到节点插入

-返回头

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

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

你是什么意思不起作用?到底发生了什么?请解释你的问题;不要让我们读代码来搞清楚。 – ChiefTwoPencils

+0

在高层次代码看起来不错,请让我们知道您面临的问题。 –

+0

此外,电话是什么样的;它是'head = insert(...);'? – ChiefTwoPencils

回答

-1

如果将节点插入到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; 

}

+0

按照共享的算法,头将被返回。这已经在if循环中完成了。 –

+0

如果你插入节点作为头部,它会在方法结尾返回头部,指向插入的节点,因为在if循环中我们做'head = node;' – djointster

+0

如果循环内部有返回声明。它不会结束该方法。 if(position == 0){node_next = head; 返回节点; } –

0

既然你的curr节点之后插入新的节点,该环路太远步骤一个节点。

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

您可以轻松地通过使用笔和纸或调试程序逐步完成代码。