设计模式之不变设计模式(二)
or E-mail:yangzhonglive@gmail.com
* @version 2013-10-12
* @since 1.0
*/
public final class PersistentStack implements Iterable {
// ----------------------------------------------------
// ---private properties
// ----------------------------------------------------
/**
* The head value of this persistent stack.
*/
private final E head;
/**
* The head of this persistent stack, and it is the tail reference of the
* stack which add element into this persistent stack
*/
private final PersistentStack tail;
/**
* The number of elements in this persistent stack.
*/
private final int size;
// ----------------------------------------------------
// ---constructor
// ----------------------------------------------------
/**
* Initial an empty persistent stack.
*/
public PersistentStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
/**
* Construct a new persistent stack based on the input persistent stack.
*
* @param head
* @param tail
*/
public PersistentStack(E head, PersistentStack tail) {
this.head = head;
this.tail = tail;
this.size = tail.size() + 1;
}
// ----------------------------------------------------
// ---API
// ----------------------------------------------------
/**
* Returns true if this persistent stack contains no elements.
*
* @return
*/
public boolean isEmpty() {
return (size == 0);
} // end isEmpty()
/**
* Retrieves, but does not remove, the head of this persistent stack. This
* method throws an exception if this persistent stack is empty.
*
* @return
*/
public E peek() {
if (isEmpty())
throw new NoSuchElementException();
else
return head;
} // end peek()
/**
* Inserts the specified element into this persistent stack
*
* @param value
* @return
*/
public PersistentStack push(E e) {
return new PersistentStack(e, this);
} // end push()
/**
* Removes the head of this persistent stack. This method throws an
* exception if this persistent stack is empty.
*
* @return
* @throws java.util.NoSuchElementException
*/
public PersistentStack pop() {
if (isEmpty())
throw new NoSuchElementException();
else
return tail;
} // end pop()
/**
* Returns the number of elements in this persistent stack.
*
* @return
*/
public int size() {
return this.size;
}
/**
* A stack is essentially a “backwards” queue, so reverse this stack
* elements to a new stack for remove element from queue.
*
* @return
* @see PersistentQueue#dequeue()
*/
public PersistentStack reverse() {
if (this.isEmpty())
return new PersistentStack();
else {
PersistentStack stack = new PersistentStack();
for (E e : this) {
stack = stack.push(e);
}// e