在单个链表中给定位置之后插入节点
问题描述:
我的代码在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循环更适合,和其他一些东西,可以重新安排更好。
答
如果它没有插入第0位和node -> new node -> next node
顺序应安排你应该改变你的代码如下图所示,因为新节点将被插入(位置+ 1)个位置是这样的。
while (count < position - 1) {
count++;
last = last.next;
}
n.data = data;
n.next = last.next;
last.next = n;
return head;
在哪个网站不起作用?你会得到什么错误?这是完整的例子吗? – TinyTheBrontosaurus