如何使用Java中参数的索引进行递归来创建remove方法?

问题描述 投票:0回答:1

我在如何启动此方法时遇到问题。我试图在我的代码中使用递归创建一个删除方法。基本上我有一个公共和私人删除方法。 remove(int)方法是公共的,应该删除列表中指定索引处的元素。我需要解决列表为空和/或删除的元素是列表中的第一个的情况。如果index参数无效,则应抛出IndexOutOfBoundsException。为了允许递归实现,此方法应解决特殊情况并委托删除(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;
    }
}
java recursion nodes singly-linked-list
1个回答
1
投票

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

Usage

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

Usage

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

Returning Node

更好的是返回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--;
}
© www.soinside.com 2019 - 2024. All rights reserved.