Java 如何在链表中的某个索引处递归插入节点
我还是一个编程新手,所以请慷慨地解释一下。我在递归实现insertAt方法时遇到问题。基本上,我需要它做的是在列表的索引中插入objectelem,而不使用任何循环Java 如何在链表中的某个索引处递归插入节点,java,recursion,linked-list,Java,Recursion,Linked List,我还是一个编程新手,所以请慷慨地解释一下。我在递归实现insertAt方法时遇到问题。基本上,我需要它做的是在列表的索引中插入objectelem,而不使用任何循环 public class ListInterfaceImplementation implements ListInterface{ private ListNode first; private ListNode last; private ListNode current; private int size = 0; pub
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);
}
公共类ListInterface实现ListInterface{
私有列表节点优先;
私有listnodelast;
私有节点电流;
私有整数大小=0;
公共列表界面实施(){
}
公共ListInterface插件(int索引,对象元素){
//TODO自动生成的方法存根
ListNode cur=新ListNode(当前);
如果(指数<0){
抛出新的IndexOutOfBoundsException();
}
if(elem==null){
抛出新的NullPointerException();
}
如果(索引==0){
ListNode节点=新的ListNode(elem);
node.getNext()=当前的.getNext();
current.getNext()=节点;
大小++;
归还这个;
}
cur=current.getNext();
返回插入(索引-1,元素);
}
这就是我到目前为止的建议。一些建议:
if(elem == null){
throw new NullPointerException();
这大概也是一个越界的例外(因为如果你跑过列表的末尾,你会得到这个)
这不应该是全局的-您希望整个状态包含在递归中
一般来说,逻辑应该是:
insertAt(list, index)
if index == 0, append the list to the node to insert and return the result
else return firstElementOfList + insertAt(listMinusFirstElement, index-1)
也就是说,我们的递归步骤通过减少列表和索引来简化。提示:您使用“cur”做什么?这是不是暗示我应该尝试一些不同的方法并完全摆脱cur?我希望我可以使用它跟踪列表中的当前节点,同时减少索引,直到它达到列表中所需的索引。我只是不确定这是否是使用cur的正确方法。我还挂断了if(index==0)循环我有指针分配的地方…分配指针时,我应该使用什么作为变量?您正在为该变量分配一个值,但以后从未使用过它。我假设这是一个疏忽。如果不使用该变量,该变量的用途是什么?关于分配指针,您需要setter方法,例如se我有一个包含所有getter和setter方法的ListNode类。你认为发布这个类会有好处吗?
insertAt(list, index)
if index == 0, append the list to the node to insert and return the result
else return firstElementOfList + insertAt(listMinusFirstElement, index-1)