我给出了指向链表头节点的指针,要添加到列表中的整数以及必须插入整数的位置。 将此节点插入到所需位置后,我需要返回头节点。在链表中的特定位置插入节点
我编写的代码由于某种原因而不起作用,并进入无限循环。
class Node {
int data;
Node next;
}
Node InsertNth(Node head, int data, int position) {
int count = 0;
Node node = head;
Node prev = null;
while(count != position){
count++;
node = node.next;
prev = node;
}
Node newNode = new Node();
newNode.data = data;
newNode.next = node;
if(count == 0){
head = newNode;
}else{
prev.next = newNode;
}
return head;
}
提示:你的'while'循环结束后,将这个:'的System.out.println( “节点=” + node.data + “上一页=” + prev.data);'其实,你需要确保'node'和'prev'首先不为空。但是我认为如果你这样做,你将能够发现错误。 – ajb