The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

The LinkedList Class

There are a number of subtle problems with the way we have been implementing lists. In a reversal of cause and effect, I will propose an alternative implementation first and then explain what problems it solves.

First, we will create a new class called LinkedList. Its instance variables are an integer that contains the length of the list and a reference to the first node in the list. LinkedList objects serve as handles for manipulating lists of Node objects.

public class LinkedList {
    int length;
    Node head;

    public LinkedList () {
        length = 0;
        head = null;

One nice thing about the LinkedList class is that it gives us a natural place to put wrapper functions like printBackwardNicely, which we can make an object method in the LinkedList class.

    public void printBackward () {
        System.out.print ("(");

        if (head != null) {
            Node tail =;
            Node.printBackward (tail);
            System.out.print (head);
        System.out.println (")");

Just to make things confusing, I renamed printBackwardNicely. Now there are two methods named printBackward: one in the Node class (the helper) and one in the LinkedList class (the wrapper). In order for the wrapper to invoke the helper, it has to identify the class explicitly (Node.printBackward).

So, one of the benefits of the LinkedList class is that it provides a nice place to put wrapper functions. Another is that it makes it easier to add or remove the first element of a list. For example, addFirst is an object method for LinkedLists; it takes an int as an argument and puts it at the beginning of the list.

    public void addFirst (int i) {
        Node node = new Node (i, head);
        head = node;

As always, to check code like this it is a good idea to think about the special cases. For example, what happens if the list is initially empty?

Last Update: 2011-01-24