Как создать метод удаления с помощью рекурсии с индексом в параметре в Java? - PullRequest
0 голосов
/ 31 марта 2019

У меня проблемы с тем, как запустить этот метод. Я пытаюсь создать метод удаления, используя рекурсии в моем коде. В основном у меня есть публичный и частный метод удаления. Публичный метод remove (int) должен удалить элемент по указанному индексу в списке. Мне нужно обратиться к случаю, когда список пуст и / или удаленный элемент является первым в списке. Если параметр индекса недействителен, должно быть выдано исключение 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;
    }
}

1 Ответ

1 голос
/ 31 марта 2019

Возвращается 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

Еще лучше вернуть 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--;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...