我试图学习在链表中插入一个节点(并返回头部),但由于某种原因它不正确。逻辑错误在链接列表(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;
}
你是什么意思不起作用?到底发生了什么?请解释你的问题;不要让我们读代码来搞清楚。 – ChiefTwoPencils
在高层次代码看起来不错,请让我们知道您面临的问题。 –
此外,电话是什么样的;它是'head = insert(...);'? – ChiefTwoPencils