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
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;
}
}
}Node data structure is only available to LinkedBag.public int getCurrentSize() {
Node currentNode = head;
int size = 0
while (currentNode != null) {
size++;
currentNode = currentNode.next;
}
return size;
}currentNode.next != nullPros:
Cons: