在单链表中给定位置之后插入节点



我的代码在Eclipse中运行良好,但在编程站点的编译器中无法正常工作。此代码是关于在给定位置添加一个节点。

Node InsertNth(Node head, int data, int position) {
Node n = new Node();
Node last = head;
int count = 0;
if (position == 0) {
n.data = data;
n.next = head;
head=n;
return n;
}
while (count < position) {
count++;
last = last.next;
}
n.data = data;
n.next = last.next;
last.next = n;
return head;
}

你在循环中走得太远,也没有检查位置是否在范围内:

Node InsertNth(Node head, int data, int position) {
Node n = new Node();
n.data = data;
if (position == 0) {
n.next = head;
return n;
}
Node last = head;
for (int count = 0; count < position-1; count++) {
if (last == null) {
return null;
}
last = last.next;
}
n.next = last.next;
last.next = n;
return head;
}

此外,for 循环更合适,其他一些东西可以更好地重新排列。

最新更新