I am implementing a doubly linked list and I have so far made it. I am now writing a method which can remove the last element in the list but I just keep getting an error saying following:
Exception in thread "main" java.lang.NullPointerException: Cannot read field "previous" because "this.trailer" is null.
Here is my code:
//creating our constructor:
//constructor taking one argument
public ListNode(T element) {
this.element = element;
}
//taking three arguments; a value and two nodes
public ListNode(T element, ListNode<T> next, ListNode<T> previous) {
this.element = element;
this.next = next;
this.previous = previous;
previous.next = this;
next.previous = this;
}
//we can use getter and setter to access various nodes in the list.
//GETTER
public T getElement() {
return this.element;
}
Here is my implementation and constructor:
public class DoublyLinkedList<T extends Comparable<T>> implements Iterable<T> {
//three instansvariabel will track how many nodes there will be in the list
private ListNode<T> header; //first node in the list (the header)
private ListNode<T> trailer; //last node in the list (the trailer)
private int size;
//creating a constructor that creates an empty list.
public DoublyLinkedList() {
header = null;
trailer = null;
size = 0;
}
Below code is to remove the last element:
public T removeLast() {
if (isEmpty()) //if empty
throw new NullPointerException();
ListNode<T> tmp = trailer; //creating a temporary that points to trailers position
trailer.previous.next = null; //the next of trailers previous assigns to null
trailer = trailer.previous; //trailers pointer moves to trailers previous node
tmp.previous = null; //tmp's previous which is that points to the "current trailer" assigns to null
return tmp.getElement(); //returns the tmp
}