关闭一个链表带有索引的递归插入

时间:2014-05-21 07:22:05

标签: java recursion head

我无法理解如何解决这个问题。因为如果我在通话前减少一个,我会得到一个负数,这会毁掉一切。不允许使用静态尾部,所以每次都需要创建一个先前的节点吗?

       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

acer + R,0 = aRcer应该是赛车手

更新代码:

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);
        }

    }

1 个答案:

答案 0 :(得分:0)

不幸的是,对于单链表,在索引处的插入效果与您预期的略有不同。由于您只能向前插入,因此单个链接列表的插入位置是提前的位置;因此,您必须明确检查index是否为0.长话短说,index是您要在前面插入的节点。< / p>

所以你需要在recInsert()

中做这样的事情
if (index == 0) {
    // insert new node at head
else {
    // Not inserting at head, so subtract 1 for "passing" head and continue
    recInsertHelper(index - 1, o, head);
}

我相信你的recInsertHelper()可以保持不变,因为你补偿recInsert()中的偏移量。