java在链表中的特定位置插入节点
我需要在位置插入一个注释。我没有错,但我的答案是错的。你能帮我更正代码吗? Link to question
Node InsertNth(Node head, int data, int position) {
Node node = new Node();
node.data = data;
if (head == null){
return node;
} else {
Node current = head;
for (int i=0; i < position-1 ; i++){
current = current.next;
}
node.next = current.next;
current.next = node;
return head;
}
}
# 1 楼答案
使用指向头部的虚拟节点有助于减少许多检查:
当然,递归解决方案也是可能的:
# 2 楼答案
这不执行IndexOutOfBoundsException