Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 3 – Linked Lists

Part 1 – The List ADT

The first step in implementing a data structure is to define its set of operations. Create a file List.java with the interface below.

interface List<E> {
    void addFront(E x);      // add x at the beginning of the list
    void addEnd(E x);        // add x at the end of the list
    void addAfter(E val, E x); // add x after the value val
    void print();            // print all the elements
    boolean empty();         // true if the list is empty
    void removeEnd();        // remove the last element
    void removeFront();      // remove the first element
    void remove(E x);        // remove the first occurrence of x
    void removeAll();        // remove all the elements
    boolean exist(E x);      // is x in the list?
    E getHead();             // the data in the head (null if empty)
}

Part 2 – Singly linked list

The class Node

A list holds a head, a reference to the first node. Each node holds the data and a reference to the next node.

class Node<E> {
    E data;
    Node<E> next;
    public Node(E data) {
        this.data = data;
        next = null;
    }
    public String toString() {
        return data + " ";
    }
}

The class LinkedList

The first three methods are given as examples.

class LinkedList<E> implements List<E> {
    private Node<E> head;

    public LinkedList() {
        head = null;
    }

    public void addFront(E x) {
        Node<E> node = new Node<>(x);
        node.next = head;
        head = node;
    }

    public void addEnd(E x) {
        if (head == null)
            addFront(x);
        else {
            Node<E> node = new Node<>(x);
            Node<E> p = head;
            while (p.next != null)
                p = p.next;
            p.next = node;
        }
    }

public void addAfter(E val, E x) {
    if (empty())
        System.out.println("empty list!!!");
    else {
        Node<E> p = head;
        while (!p.data.equals(val) && p.next != null)
            p = p.next;
        if (!p.data.equals(val))
            System.out.println("The list doesn't contain the value " + val);
        else {
            Node<E> node = new Node<>(x);
            node.next = p.next;
            p.next = node;
        }
    }
}
}

Now implement the other methods.

public void print() {
    // ToDo
}
Solution
public void print() {
    Node<E> p = head;
    while (p != null) {
        System.out.print(p);       // Node.toString() adds a space
        p = p.next;
    }
    System.out.println();
}
public boolean empty() {
    // ToDo
}
Solution
public boolean empty() {
    return head == null;
}

🚩 Check that the list is not empty!

🚩 Check whether the list contains only one element!

public void removeEnd() {
    // ToDo
}
Solution
public void removeEnd() {
    if (empty())
        return;
    if (head.next == null) {       // only one element
        head = null;
        return;
    }
    Node<E> p = head;
    while (p.next.next != null)    // stop at the node before the last
        p = p.next;
    p.next = null;
}

🚩 Check that the list is not empty!

public void removeFront() {
    // ToDo
}
Solution
public void removeFront() {
    if (!empty())
        head = head.next;
}

🚩 Check that the list is not empty!

🚩 The reference you move must stop at the predecessor of the node to remove!

public void remove(E x) {
    // ToDo
}
Solution
public void remove(E x) {
    if (empty())
        return;
    if (head.data.equals(x)) {     // x is the first element
        head = head.next;
        return;
    }
    Node<E> p = head;              // p: the predecessor of the node to remove
    while (p.next != null && !p.next.data.equals(x))
        p = p.next;
    if (p.next != null)
        p.next = p.next.next;      // bypass the node
}
public void removeAll() {
    // ToDo
}
Solution
public void removeAll() {
    head = null;                   // the garbage collector frees the nodes
}
public boolean exist(E x) {
    // ToDo
}
Solution
public boolean exist(E x) {
    Node<E> p = head;
    while (p != null) {
        if (p.data.equals(x))
            return true;
        p = p.next;
    }
    return false;
}
public E getHead() {
    // ToDo
}
Solution
public E getHead() {
    if (empty())
        return null;
    return head.data;
}

Test your linked list

LinkedList<Integer> L = new LinkedList<>();
L.addFront(3);
L.addFront(2);
L.addFront(1);
L.addEnd(4);
L.addAfter(2, 200);
L.addAfter(200, 9);     // 200 is not cached by Java: equals() is needed
L.addAfter(7, 5);       // 7 is not in the list
L.print();
L.removeFront();
L.removeEnd();
L.remove(200);
L.print();
System.out.println(L.exist(9) + " " + L.exist(7) + " " + L.getHead());
L.removeAll();
System.out.println(L.empty() + " " + L.getHead());

Expected output:

The list doesn't contain the value 7
1 2 200 9 3 4 
2 9 3 
true false 2
true null

Part 3 – Doubly linked list

The class DNode

A doubly linked list keeps a head and a tail, a reference to the last node. Each node refers to its successor and its predecessor.

class DNode<E> {
    E data;
    DNode<E> next;
    DNode<E> previous;
    public DNode(E data) {
        this.data = data;
        next = null;
        previous = null;
    }
    public String toString() {
        return data + " ";
    }
}

The class DoublyLinkedList

class DoublyLinkedList<E> implements List<E> {
    private DNode<E> head, tail;

    public DoublyLinkedList() {
        head = null;
        tail = null;
    }
    // ... the methods below
}

🚩 Update the tail if the list is empty!

public void addFront(E x) {
    // ToDo
}
Solution
public void addFront(E x) {
    DNode<E> node = new DNode<>(x);
    if (empty()) {
        head = tail = node;        // the only node is also the tail
    } else {
        node.next = head;
        head.previous = node;
        head = node;
    }
}

🚩 Update the head if the list is empty!

public void addEnd(E x) {
    // ToDo
}
Solution
public void addEnd(E x) {
    if (empty()) {
        addFront(x);
        return;
    }
    DNode<E> node = new DNode<>(x);
    node.previous = tail;
    tail.next = node;
    tail = node;
}

🚩 Check that the list is not empty, and that val exists!

🚩 Update the previous of the successor and the next of the predecessor!

🚩 If val is the last element, the tail changes!

public void addAfter(E val, E x) {
    // ToDo
}
Solution
public void addAfter(E val, E x) {
    if (empty()) {
        System.out.println("empty list!!!");
        return;
    }
    DNode<E> p = head;
    while (p != null && !p.data.equals(val))
        p = p.next;
    if (p == null) {
        System.out.println("The list doesn't contain the value " + val);
        return;
    }
    if (p == tail) {               // after the last node
        addEnd(x);
        return;
    }
    DNode<E> node = new DNode<>(x);
    node.previous = p;
    node.next = p.next;
    p.next.previous = node;        // the successor points back to the new node
    p.next = node;                 // the predecessor points to the new node
}
public void print() {
    // ToDo
}
public void printReverse() {
    // ToDo
}
Solution
public void print() {
    for (DNode<E> p = head; p != null; p = p.next)
        System.out.print(p);
    System.out.println();
}

public void printReverse() {       // extra: walk backwards from the tail
    for (DNode<E> p = tail; p != null; p = p.previous)
        System.out.print(p);
    System.out.println();
}
public boolean empty() {
    // ToDo
}
Solution
public boolean empty() {
    return head == null;
}

🚩 Check that the list is not empty, and whether it contains only one element!

🚩 Set the next of the new last element to null!

public void removeEnd() {
    // ToDo
}
Solution
public void removeEnd() {
    if (empty())
        return;
    if (head == tail) {            // only one element
        head = tail = null;
        return;
    }
    tail = tail.previous;
    tail.next = null;
}

🚩 Check that the list is not empty!

🚩 Update the tail if the list contains one element!

🚩 Set the previous of the new head to null!

public void removeFront() {
    // ToDo
}
Solution
public void removeFront() {
    if (empty())
        return;
    if (head == tail) {            // only one element
        head = tail = null;
        return;
    }
    head = head.next;
    head.previous = null;
}

🚩 The first and the last node are special cases!

🚩 Otherwise update the next of the predecessor and the previous of the successor!

public void remove(E x) {
    // ToDo
}
Solution
public void remove(E x) {
    DNode<E> p = head;
    while (p != null && !p.data.equals(x))
        p = p.next;
    if (p == null)
        return;                    // not found (or empty list)
    if (p == head) { removeFront(); return; }
    if (p == tail) { removeEnd(); return; }
    p.previous.next = p.next;      // the predecessor skips p
    p.next.previous = p.previous;  // the successor skips p
}
public void removeAll() {
    // ToDo
}
public boolean exist(E x) {
    // ToDo
}
public E getHead() {
    // ToDo
}
Solution
public void removeAll() {
    head = tail = null;
}

public boolean exist(E x) {
    for (DNode<E> p = head; p != null; p = p.next)
        if (p.data.equals(x))
            return true;
    return false;
}

public E getHead() {
    return empty() ? null : head.data;
}

Test your doubly linked list

DoublyLinkedList<String> D = new DoublyLinkedList<>();
D.addEnd("B");
D.addFront("A");
D.addEnd("D");
D.addAfter("B", "C");
D.addAfter("D", "E");   // after the last node: the tail changes
D.print();
D.printReverse();
D.remove("C");
D.removeFront();
D.removeEnd();
D.print();
D.printReverse();
System.out.println(D.exist("B") + " " + D.getHead());

Expected output:

A B C D E 
E D C B A 
B D 
D B 
true B

Part 4 – Use the JDK

Challenge 1 – A playlist with a list iterator

Start from the playlist Intro, Song A, Song B, Song C, Outro. In one walk with a ListIterator, insert "Song X" right after "Song B" and remove "Song C". Then move the last song to the front. Inserting or removing at the iterator’s position is O(1)O(1): this is where a linked list shines.

Solution
LinkedList<String> playlist = new LinkedList<>(
        List.of("Intro", "Song A", "Song B", "Song C", "Outro"));

// insert "Song X" after "Song B", and remove "Song C", in one walk
ListIterator<String> it = playlist.listIterator();
while (it.hasNext()) {
    String s = it.next();
    if (s.equals("Song B"))
        it.add("Song X");        // inserted after the current song: O(1)
    else if (s.equals("Song C"))
        it.remove();             // removes the current song: O(1)
}
System.out.println(playlist);

playlist.addFirst(playlist.removeLast());   // move the last song to the front
System.out.println(playlist);
System.out.println("first: " + playlist.getFirst()
                   + ", last: " + playlist.getLast());

Expected output:

[Intro, Song A, Song B, Song X, Outro]
[Outro, Intro, Song A, Song B, Song X]
first: Outro, last: Song X

Challenge 2 – Remove duplicates, keep the order

Given the marks 15 12 15 18 12 9 18 20, build the list of distinct marks in their first order of appearance, then the same marks sorted. Which set keeps the order, which one sorts?

Solution
java.util.List<Integer> marks = List.of(15, 12, 15, 18, 12, 9, 18, 20);
Set<Integer> distinct = new LinkedHashSet<>(marks);   // keeps the first order
System.out.println(distinct);
System.out.println(new TreeSet<>(marks));             // sorted instead
System.out.println(new ArrayList<>(distinct).get(2)); // back to a list

Expected output:

[15, 12, 18, 9, 20]
[9, 12, 15, 18, 20]
18

Challenge 3 – ArrayList or LinkedList?

Measure, for n=100 000n = 100\,000: inserting nn elements at position 0, then reading 10,000 elements by position with get(i), in both lists.

Solution
int n = 100_000;
java.util.List<Integer> arr = new ArrayList<>();
java.util.List<Integer> linked = new LinkedList<>();

long t0 = System.nanoTime();
for (int i = 0; i < n; i++) arr.add(0, i);        // insert at the front
long t1 = System.nanoTime();
for (int i = 0; i < n; i++) linked.add(0, i);
long t2 = System.nanoTime();
System.out.printf("add at front : ArrayList %7.1f ms, LinkedList %7.1f ms%n",
                  (t1 - t0) / 1e6, (t2 - t1) / 1e6);

long sum = 0;
t0 = System.nanoTime();
for (int i = 0; i < n; i += 10) sum += arr.get(i);    // access by position
t1 = System.nanoTime();
for (int i = 0; i < n; i += 10) sum += linked.get(i);
t2 = System.nanoTime();
System.out.printf("get(i)       : ArrayList %7.1f ms, LinkedList %7.1f ms%n",
                  (t1 - t0) / 1e6, (t2 - t1) / 1e6);

Sample output (your times will differ):

add at front : ArrayList   477.1 ms, LinkedList     5.3 ms
get(i)       : ArrayList     0.6 ms, LinkedList   522.7 ms

Each list wins one test by about two orders of magnitude, exactly as the cost table of Chapter 3 predicts: inserting at the front shifts the whole array, while get(i) walks along the linked list.