Я пытаюсь реализовать структуру данных связанного списка, используя java, она отлично работает для вставки или удаления первых элементов, но не может удалить последний элемент с помощью метода removeLast ().
Класс узла My Linked List:
открытый класс LLNode {
Строковое значение;
LLNode следующий;
public LLNode(String value){
this.value = value;
this.next = null;
}
}
Класс My Linked List, который содержит головной узел:
public class LL {
LLNode head;
public LL(){
this.head = null;
}
public void insertHead(LLNode input){
input.next = head;
this.head = input;
}
public void removeFirst(){
this.head = this.head.next;
}
public void removeLast(){
if (this.head == null || this.head.next == null){
this.head = null;
return;
}
LLNode current = this.head;
LLNode tmphead = current;
while(current.next.next != null){
current = current.next;
}
current.next.next = null;
this.head = tmphead ;
}
public void printAll(){
LLNode current = this.head;
while(current != null){
System.out.print(current.value+" ");
current = current.next;
}
System.out.println();
}
public static void main( String[] args){
LL test = new LL();
LL test2 = new LL();
String[] eben = {"one","two","three","four","five","six"};
for(int i =0;i<eben.length;i++){
test.insertHead(new LLNode(eben[i]));
}
test.printAll();
test.removeFirst();
test.printAll();
test.removeLast();
test.printAll();
}
}
Вывод такой:
six five four three two one
five four three two one
five four three two one
даже если бы это было так:
six five four three two one
five four three two one
five four three two
Что не так с моей реализацией?