【问题标题】:Off by one linked list recursive insert with index通过一个带索引的链表递归插入
【发布时间】: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 = 温度;返回;

标签: java recursion head


【解决方案1】:

不幸的是,对于单链表,在索引处插入的工作方式与您预期的略有不同。由于您只能向前插入,因此单链表的插入是您期望的位置提前;因此,您必须明确检查 index 是否为 0。长话短说,index 是您要插入前面的节点。

所以你需要在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() 中的偏移量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多