Problems with Array Implementation

  1. Fixed Size
    1. May become full
    2. May have wasted space
  2. Resizing is possible, but requires overhead.

One solution: Linked list.

Linked Data

Related Notes: Linked List (CS2600)

Linked List: Linear data structure in which each element is:

  1. Dynamically allocated, and
  2. Elements point to each other.

Data is stored as a chain of nodes rather than a contiguous block of memory.

A Very Lame Analogy: Empty classroom

Example: Node as a private inner class for a singly-linked list

public final class LinkedBag<T> implements BagInterface<T> {
  private Node head;
  private int entries;
  public LinkedBag() {
      head = null;
      entries = 0;
  }
  /** (Implementation of BagInterface here) */
  /**
  * Private node inner-class
  */
  private class Node<T> {
      private T data; // The data stored in this node.
      private Node next; // Reference to next node in chain.
      private Node (T data) {
          this(data, null);
      }
      private Node (T data, Node next) {
          this.data = data;
          this.next = next;
      }
  }
}

Example: Traversal

Example: Traversing a linked list

public int getCurrentSize() {
  Node currentNode = head;
  int size = 0
  while (currentNode != null) {
      size++;
      currentNode = currentNode.next;
  }
  return size;
}

Pros and Cons

Pros:

Cons: