Hello, I am trying to implement the linked list data structure using java, it works fine for insertion or removing first elements but fails to remove the last element via using the removeLast() method.
My Linked List Node class: public class LLNode { String value; LLNode next;
public LLNode(String value){
this.value = value;
this.next = null;
}
}
My Linked List class that holds a head Node:
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();
}
}
The output is such:
six five four three two one
five four three two one
five four three two one
even tho it had to be like this:
six five four three two one
five four three two one
five four three two
What is wrong with my implementation ?