My generic implementation of the Stack using the Composite Design pattern is as follows:
EmptyStack.java
public final class EmptyStack<E> implements IImmutableStack<E> {
@Override
public IImmutableStack<E> pop() { return null; }
@Override
public IImmutableStack<E> push(E value) { return new NonEmptyStack<E>(value, this); }
@Override
public E peek() { return null; }
@Override
public int getSize() { return 0; }
@Override
public boolean isEmpty() { return true; }
}
NonEmptyStack.java
public final class NonEmptyStack<E> implements IImmutableStack<E> {
private final E head;
private final IImmutableStack<E> tail;
public NonEmptyStack(E head, IImmutableStack<E> tail) {
this.head = head;
this.tail = tail;
}
@Override
public IImmutableStack<E> pop() {
return this.tail;
}
@Override
public NonEmptyStack<E> push(E e) {
return new NonEmptyStack<E>(e, this);
}
@Override
public E peek() {
return this.head;
}
public static <E> IImmutableStack<E> empty() {
return new EmptyStack<E>();
}
@Override
public boolean isEmpty() {
return (head == null && tail == null);
}
@Override
public int getSize() {
return isEmpty() ? 0 : 1 + tail.getSize();
}
}
The stack gets used as the underlaying object for iterating a BST, this is the implementation
BST Iterator
public final class DictionaryIterator<K extends Comparable<K>, E> implements Iterator<K> {
private final IImmutableStack<Node<K,E>> stack;
public DictionaryIterator(Node<K,E> root) {
stack = NonEmptyStack.empty();
init(root);
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public K next() {
Node<K,E> incoming = stack.peek();
if (incoming != null && incoming.getRight() != null) {
Node<K,E> node = incoming.getRight();
while (node != null) {
stack.push(node);
node = node.getLeft();
}
}
stack.pop();
return incoming == null ? null : incoming.getKey();
}
private void init(Node<K, E> root) {
Node<K,E> node = root;
while (node != null) {
stack.push(node);
node = node.getLeft();
}
}
}
However, when the iterator gets invoked and used, it seems that there is nothing in the Stack. I've tried debugging exhaustively without any avail, any suggestions as to what might be going wrong in the way I implemented the above components?
Aucun commentaire:
Enregistrer un commentaire