如何在Java的参数中使用索引的递归创建删除方法?

我在如何启动此方法时遇到问题。我正在尝试使用代码中的递归创建一个 remove 方法。基本上我有一个公共和私人的删除方法。remove(int) 方法(公共)应删除列表中指定索引处的元素。我需要解决列表为空和/或删除的元素是列表中第一个元素的情况。如果索引参数无效,则应引发“索引超出边界异常”。为了允许递归实现,此方法应解决特殊情况并委托删除(int,int,Node)以进行递归。


下面是类:


public class SortedLinkedList<E extends Comparable<E>>

{

    private Node first;

    private int size;

    // ...

}

代码如下:


public void remove(int index)

{

    if(index < 0 || index > size)

    {

        throw new IndexOutOfBoundsException();

    }

    remove(index++, 0, first);

    if (index == 0)

    {

        if(size == 1)

        {

            first = null;

        }

        else

        {

            first = first.next;

        }

    }

    size--;

}

和私有方法:


private void remove(int index, int currentIndex, Node n)

{

    if(index == currentIndex)

    {

        remove(index, currentIndex, n.next);

    }

    remove(index, currentIndex, n.next.next);

}

私人课程:


private class Node

{

    private E data;

    private Node next;


    public Node(E data, Node next)

    {

        this.data = data;

        this.next = next;

    }

}


扬帆大鱼
浏览 106回答 1
1回答

万千封印

返回void使用两个索引private void remove(int index, int current, Node n) {&nbsp; if (n == null || index <= 0 || (index == 1 && n.next == null) {&nbsp; &nbsp; throw new IndexOutOfBoundsException();&nbsp; }&nbsp; if (current == index - 1) {&nbsp; &nbsp; // Remove 'n.next'.&nbsp; &nbsp; n.next = n.next.next;&nbsp;&nbsp; } else {&nbsp; &nbsp; remove(index, current + 1, n.next);&nbsp; }}用法public void remove(int index) {&nbsp; if (first == null || index < 0) {&nbsp; &nbsp; throw new IndexOutOfBoundsException();&nbsp; }&nbsp; if (index == 0) {&nbsp; &nbsp; // Remove 'first'.&nbsp; &nbsp; first = first.next;&nbsp; } else {&nbsp; &nbsp; remove(index, 0, first);&nbsp; }&nbsp; size--;}使用一个索引只需要一个索引:private void remove(int index, Node n) {&nbsp; if (n == null || index <= 0 || (index == 1 && n.next == null) {&nbsp; &nbsp; throw new IndexOutOfBoundsException();&nbsp; }&nbsp; if (index == 1) {&nbsp; &nbsp; // Remove 'n.next'.&nbsp; &nbsp; n.next = n.next.next;&nbsp;&nbsp; } else {&nbsp; &nbsp; remove(index - 1, n.next);&nbsp; }}用法public void remove(int index) {&nbsp; if (first == null || index < 0) {&nbsp; &nbsp; throw new IndexOutOfBoundsException();&nbsp; }&nbsp; if (index == 0) {&nbsp; &nbsp; // Remove 'first'.&nbsp; &nbsp; first = first.next;&nbsp; } else {&nbsp; &nbsp; remove(index, first);&nbsp; }&nbsp; size--;}返回Node更好的是返回而不是:Nodevoidprivate Node remove(int index, Node n) {&nbsp; if (n == null || index < 0) {&nbsp; &nbsp; throw new IndexOutOfBoundsException();&nbsp; }&nbsp; if (index == 0) {&nbsp; &nbsp; // Remove 'n' and return the rest of the list.&nbsp; &nbsp; return n.next;&nbsp;&nbsp; }&nbsp; // 'n' stays. Update the rest of the list and return it.&nbsp; n.next = remove(index - 1, n.next);&nbsp; return n;}用法public void remove(int index) {&nbsp; first = remove(index, first);&nbsp; size--;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java