Я реализую метод remove()
настраиваемого класса LinkedList
, но он не удаляет какие-либо элементы из списка, и я не могу понять, почему.Пользовательский LinkedList: метод удаления не работает должным образом
Вот как я это делаю:
public void remove(int position) {
if (position < 0 || position >= size) {
throw new IndexOutOfBoundsException(
"position should be beween 0 and size - 1");
}
Cell current = top;
for (int i = 0; i < position; i++) {
current = current.next;
}
current = current.next.next;
size--;
}
Этот метод пытается удалить элемент между 2 узлами (удаление первого узла и последние случаи узла игнорируются).
Это тест я выполняется, и после попытки удалить элемент с индексом 2, он по-прежнему печатает список отверстий:
CustomList<String> list = new CustomList<String>();
list.add("Hello");
list.add("morena");
list.add("What");
list.add("Miranda");
list.add("Aston");
list.remove(2);
list.printAll();
Для завершения, здесь полное осуществление списка:
public class CustomList<T> {
private class Cell {
T data;
Cell next;
public Cell(T data) {
this.data = data;
}
}
private Cell top;
private int size;
public void add(T data) {
addAtEndInOn(data);
size++;
}
/**
* adds an item at the end of the list in O(n) by iterating the whole list
* before adding the node
*/
private void addAtEndInOn(T data) {
if (top == null) {
top = new Cell(data);
} else {
Cell current = top;
while (current.next != null) {
current = current.next;
}
current.next = new Cell(data);
}
}
public void remove(int position) {
if (position < 0 || position >= size) {
throw new IllegalArgumentException(
"position should be a positive number");
}
Cell current = top;
for (int i = 0; i < position; i++) {
current = current.next;
}
current = current.next.next;
size--;
}
public void printAll() {
Cell current = top;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
}