我正在尝试以递归方式在指定索引处添加列表节点。我的意思是 List 类 addAtRec() 调用 ListNode 类中的 addAtRec() ,该方法应该是递归的。
这就是我所做的:
列表:
public class List implements Cloneable {
private ListNode firstNode;
private ListNode lastNode;
private String name;
private int counter;
public List(){
this("list");
}
public void addAtRec(Object obj, int k)
{
if(firstNode != null)
firstNode.addAtRec(obj, k, firstNode);
}
}
那当然只是相关的部分......
列表节点:
public class ListNode implements Cloneable {
Object data;
ListNode nextNode;
public ListNode(Object o){
this(o,null);
}
public ListNode(Object o,ListNode node){
data=o;
nextNode=node;
}
public void addAtRec(Object obj, int k, ListNode current) throws ListIndexOutOfBoundsException {
if(current.nextNode == null && k != 0)
throw new ListIndexOutOfBoundsException(); //line 47
if(k == 0)
{
ListNode l = new ListNode(obj);
l.nextNode = current.nextNode;
current.nextNode = l;
}
current = current.nextNode;
addAtRec(obj, k, current); //line 55
k--;
}
ListIndexOutOfBoundsException:
public class ListIndexOutOfBoundsException extends RuntimeException {
}
我的 main() 方法:
String s1 = "Objects";
String s2 = "to";
String s3 = "check";
String s4 = "are";
String s5 = "strings";
List list = new List("My list");
list.insertAtBack(s1);
list.insertAtBack(s2);
list.insertAtBack(s3);
list.insertAtBack(s4);
list.insertAtBack(s5);
list.addAtRec(s3, 2);
和错误:
Exception in thread "main" ListIndexOutOfBoundsException
at ListNode.addAtRec(ListNode.java:47)
at ListNode.addAtRec(ListNode.java:55)
at ListNode.addAtRec(ListNode.java:55)
at ListNode.addAtRec(ListNode.java:55)
at ListNode.addAtRec(ListNode.java:55)
at List.addAtRec(List.java:158)
我做错了什么?感谢您的时间和答案。