Удаление элемента по индексу Linkedlist
Ребята помогите реализовать метод removeAt. Метод реализовал,но кроме 0 элемента не корректно работает, прошу помочь.
public void removeAt(int index) throws Exception {
if (count == 0) {
throw new Exception("LinkedList is empty");
}
if (index < 0 || index >= count) {
throw new IndexOutOfBoundsException("Invalid element");
}
if (first == null) {
return;
}
Node current = first;
if (index == 0) {
first = current.next;
return;
}
for (int i = 0; current != null && i < index - 1; i++) {
current = current.next;
if (current == null || current.next == null) {
return;
}
Node next = current.next.next;
current.next = next;
}
count--;
}
public class Main {
public static void main(String[] args) throws Exception {
List list = new LinkedList();
list.add(8);
list.add(15);
list.add(12);
list.add(7);
list.add(8);
list.add(8);
list.removeAt(5);
Iterator iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}