【发布时间】:2014-10-16 02:58:08
【问题描述】:
我在编程方面还是个新手,所以请慷慨解说。我在递归实现 insertAt 方法时遇到了麻烦。基本上我需要它做的是在不使用任何循环的情况下将 Object elem 插入到列表的索引中。
public class ListInterfaceImplementation implements ListInterface{
private ListNode first;
private ListNode last;
private ListNode current;
private int size = 0;
public ListInterfaceImplementation(){
}
public ListInterface insertAt(int index, Object elem) {
// TODO Auto-generated method stub
ListNode cur = new ListNode(current);
if(index < 0){
throw new IndexOutOfBoundsException();
}
if(elem == null){
throw new NullPointerException();
}
if(index == 0){
ListNode node = new ListNode(elem);
node.getNext() = current.getNext();
current.getNext() = node;
size++;
return this;
}
cur = current.getNext();
return insertAt(index -1, elem);
}
这是我目前所拥有的。
【问题讨论】:
-
提示:你在用“cur”做什么?
-
这是暗示我应该尝试一些不同的东西并完全摆脱 cur 吗?我希望我可以使用它来跟踪列表中的当前节点,同时减少索引,直到它到达列表中所需的索引。我只是不确定这是否是使用 cur 的正确方法。我也挂断了 if(index==0) 循环,在那里我有指针分配......在分配指针时我应该使用什么作为变量?
-
您正在为该变量分配一个值,但您以后永远不会使用它。我以为这是一个疏忽。不使用变量的目的是什么?
-
关于指针的赋值,需要setter方法,比如setNext(ListNode node)。
-
我有一个 ListNode 类,其中包含我所有的 getter 和 setter 方法。您认为也发布该课程会有益吗?
标签: java recursion linked-list