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

How to create a remove method using recursion with an index in the parameter in Java?

我无法启动此方法。我正在尝试在我的代码中使用递归创建一个删除方法。基本上我有一个 public 和私有删除方法。 remove(int) 方法 public 应该删除列表中指定索引处的元素。我需要解决列表为空的情况 and/or 删除的元素是列表中的第一个。如果索引参数无效,则应抛出 IndexOutOfBoundsException。为了允许递归实现,此方法应解决特殊情况并委托 remove(int, int, Node) 进行递归。

这是 class:

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

私人class:

private class Node
{
    private E data;
    private Node next;

    public Node(E data, Node next)
    {
        this.data = data;
        this.next = next;
    }
}

返回 void

使用两个索引

private void remove(int index, int current, Node n) {
  if (n == null || index <= 0 || (index == 1 && n.next == null) {
    throw new IndexOutOfBoundsException();
  }
  if (current == index - 1) {
    // Remove 'n.next'.
    n.next = n.next.next; 
  } else {
    remove(index, current + 1, n.next);
  }
}

用法

public void remove(int index) {
  if (first == null || index < 0) {
    throw new IndexOutOfBoundsException();
  }
  if (index == 0) {
    // Remove 'first'.
    first = first.next;
  } else {
    remove(index, 0, first);
  }
  size--;
}

使用一个索引

只需要一个索引:

private void remove(int index, Node n) {
  if (n == null || index <= 0 || (index == 1 && n.next == null) {
    throw new IndexOutOfBoundsException();
  }
  if (index == 1) {
    // Remove 'n.next'.
    n.next = n.next.next; 
  } else {
    remove(index - 1, n.next);
  }
}

用法

public void remove(int index) {
  if (first == null || index < 0) {
    throw new IndexOutOfBoundsException();
  }
  if (index == 0) {
    // Remove 'first'.
    first = first.next;
  } else {
    remove(index, first);
  }
  size--;
}

返回 Node

更好的是 return Node 而不是 void:

private Node remove(int index, Node n) {
  if (n == null || index < 0) {
    throw new IndexOutOfBoundsException();
  }
  if (index == 0) {
    // Remove 'n' and return the rest of the list.
    return n.next; 
  }
  // 'n' stays. Update the rest of the list and return it.
  n.next = remove(index - 1, n.next);
  return n;
}

用法

public void remove(int index) {
  first = remove(index, first);
  size--;
}