Я пытаюсь реализовать структуру данных связанных списков с помощью java, она отлично работает для вставки или удаления первых элементов, но не удаляет последний элемент с помощью метода removeLast().java-реализация структуры данных связанных списков
My Linked List Класс узла: открытый класс LLNode { Строковое значение; LLNode next;
public LLNode(String value){
this.value = value;
this.next = null;
}
}
Мой Linked класс список, который держит голову Узел:
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
Что не так с моей реализацией?
Это либо J2ME или домашнее задание, так как нет никакой другой земной причины, почему вы хотели бы сделать это. – skaffman
egad, если вспомнить из моего класса структур данных в 1980 году, этот пример очищается примерно на 99% с помощью дозорного. –