【发布时间】:2017-03-07 05:17:06
【问题描述】:
给我一个指向链表头节点的指针,一个要添加到链表中的整数以及必须插入该整数的位置。 将此节点插入所需位置后,我需要返回头节点。
我编写的代码由于某种原因无法运行并进入无限循环。
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 = " + node.data + " prev = " + prev.data);实际上,您需要先确保node和prev不为空。但我认为如果你这样做,你将能够发现错误。
标签: java algorithm data-structures linked-list