Last active
September 2, 2019 22:17
-
-
Save camertron/84b2afb3e7cf8d83ff0008fade67f1cf to your computer and use it in GitHub Desktop.
Using a null object as a list terminator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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