Linked Lists in Java

Notes from Josh Hug's lecture videos.

A linked list is a recursive object that contains a value and the next element in the list, which is another instance of itself.

public class IntNode{
    private int item;
    private IntNode next;
    public IntNode(int item, IntList next){
        this.item = item;
        this.next = next;
    }
}

This is really bad, though, and it's a pain for users to use, so we can improve it.

Improving the IntNode

In order to start fixing our IntNode let's build a new class that uses it, SLList.

public class SLList {
    private IntNode first;
    public SLList(int x) {
        first = new IntNode(x, null)
    }
}

It's somewhat better, since there's no more need to, when creating a linked list, specify a null, e.g. new IntNode(6, null).

Let's implement getters and setters for the first item in the list. We'll also nest the IntNode class inside of our SLList. Java supports nested classes!

Now there's no more need for users, when constructing lists, to nest a bunch of new IntNode() calls, and they can just use the addFirst method if they want to extend the list.

This is Better

This is Cringe

SLList L = new SLList(3);

IntNode L = new IntNode(9, new IntNode(6, new IntNode(3, null)))

L.addFirst(6);

L.addFirst(9);

Improving the SLList

Now that we've got our basic SLList structure down, we can improve it further by adding more methods for the user.

The Empty List

Let's add another constructor so that we can account for having an empty SLList.

This works fine for everything but `addLast`, because in that method, we try to access the .next of first, which is not going to work because it is null. Let's see how we can fix that.

Sentinel Node

Instead of using a special case, we can represent the empty list using a sentinel node, a special node that is always there.

Because we rewrote our code in this way, we have the following invariants in mind!

  • The first item in the linked list will always be at sentinel.next.

  • In the addLast method, temp will never be null.

We don't have to write special cases for null anymore.

Last updated

Was this helpful?