【发布时间】:2014-05-21 07:22:04
【问题描述】:
我无法理解如何处理这个问题。因为如果我在通话前减一,我会得到负数,这会破坏一切。静态tail是不允许的,每次都需要创建一个前一个Node吗?
public void recInsert(Object o, int index){
//No invalid inputs
if(index < 0){
throw new RuntimeException("Clearly out of bounds");
}
if(isEmpty() && index != 0){
throw new RuntimeException("Can't insert there on empty list");
}
recInsertHelper(index, o, head);
}
private void recInsertHelper(int index, Object o, Node current){
if(current == null){
throw new RuntimeException("too big");
}
if(index == 0){
current.next = new Node(o, current.next);
} else {
recInsertHelper(index-1, o, current.next);
}
}
我什至尝试将基本情况更改为答案@Recursively add a node at a certain index on Linked List
宏碁 + R, 0 = aRcer 应该是 Racer
更新代码:
public void recInsert(Object o, int index){
//No invalid inputs
if(index < 0){
throw new RuntimeException("Clearly out of bounds");
}
if(isEmpty() && index != 0){
throw new RuntimeException("Can't insert there on empty list");
}
if(!isEmpty() && index == 0){
head = new Node(o, head);
} else {
recInsertHelper(index - 1, o, head);
}
}
private void recInsertHelper(int index, Object o, Node current){
if(current == null){
throw new RuntimeException("too big");
}
if(index == 0){
current.next = new Node(o, current.next);
} else {
recInsertHelper(index - 1, o, current.next);
}
}
【问题讨论】:
-
只是提示,您应该抛出一个比
RuntimeException更具描述性的异常。如IndexOutOfBoundsException。 -
你是什么意思,减一?
-
它不应该在右边。因此,它不是 0 索引而是进入 1 索引。是的,我现在正在处理它,很抱歉遗漏了 -- 或 -1。
-
好吧,如果您将
current.next设置为新节点,您还希望该节点插入到哪里? -
好吧,我在唯一一个发现与我相似的问题上尝试了代码:Node temp = new Node(o); temp.next = current.next; current.next = 温度;返回;