One solution: Linked list.
Related Notes: Linked List (CS2600)
- (These notes explain it better than the analogy)
- tl;dr: We’re making a singly-linked list, which doesn’t have a tail (you can’t traverse backwards).
Linked List: Linear data structure in which each element is:
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() { = null; head = 0; entries } /** (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; } } }
- Conventionally we put our inner-classes at the bottom of a class, after fields and methods, respectively.
- This
Node
data structure is only available toLinkedBag
.
Example: Traversing a linked list
public int getCurrentSize() { Node currentNode = head; int size = 0 while (currentNode != null) { ++; size= currentNode.next; currentNode } return size; }
- Common Mistakes:
- Doing
currentNode.next != null
- Using the head node instead of a reference to it
- (You’ll destroy your data)
Pros:
Cons: