Skip to content

Instantly share code, notes, and snippets.

@camertron
Last active September 2, 2019 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camertron/84b2afb3e7cf8d83ff0008fade67f1cf to your computer and use it in GitHub Desktop.
Save camertron/84b2afb3e7cf8d83ff0008fade67f1cf to your computer and use it in GitHub Desktop.
Using a null object as a list terminator
interface INode<T> {
boolean hasNext();
Node<T> getNext();
T getValue();
}
class Node<T> implements INode<T> {
private T value;
private INode<T> next;
public Node(T value) {
this.value = value;
}
public boolean hasNext() {
return true;
}
public Node<T> getNext() {
return this.next;
}
public T getValue() {
return value;
}
}
class TerminatorNode<T> implements INode<T> {
public boolean hasNext() {
return false;
}
public Node<T> getNext() {
return this;
}
public T getValue() {
return null;
}
}
class List<T> {
private Node<T> start;
public List() {
this.start = new TerminatorNode<T>()
}
public Node<T> get(int index) {
int counter = 0;
for (INode n = start; n.hasNext(); n = n.getNext()) {
if (counter == index) {
return n.getValue();
}
counter ++;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment