1

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
}
Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
Sopie
  • 19
  • 1
  • 1
    You may want want to add the entire code of your list and prepare [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your exception says - `"this.trailer" is null`, which makes me believe the root of the problem is somewhere in your add methods. Currently there is not enough information to diagnose the issue. As a side note, if you remove elements, naturally you must decrement the size, which you don't. – Chaosfire Apr 08 '22 at 14:05
  • About your seconds question, it should be a separate question altogether. And it's impossible to diagnose it without the code of the method. – Chaosfire Apr 08 '22 at 14:06
  • Try running through your code with a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems#:~:text=A%20debugger%20is%20a%20program,while%20your%20program%20is%20running.). – Alias Cartellano Apr 08 '22 at 22:06

0 Answers0