主類
package DataStructures;
public class ArrayStack {
private Object[] theArray;
private int topOfStack;
static final int DEFAULT_CAPACITY = 10;
/**
* Construct the stack.
*
*/
public ArrayStack() {
this(DEFAULT_CAPACITY);
}
* @param capacity
* teh capacity.
public ArrayStack(int capacity) {
public boolean IsEmpty() {
return topOfStack == -1;
public boolean IsFull() {
return topOfStack == theArray.length - 1;
public void MakeEmpty() {
topOfStack = -1;
* Insert a new item into the stack, if not already full.
* @param x
* th item to insert.
* @throws Overflow
* if stack is already full.
public void Push(Object x) throws Overflow {
if (IsFull())
throw new Overflow();
theArray[++topOfStack] = x;
* Get the most recently inserted item in the stack. Dos not alter the
* stack.
* @return the most recently inserted item, or null, if empty.
public Object Top() {
if (IsEmpty())
return null;
return theArray[topOfStack];
public void Pop() throws Underflow {
throw new Underflow();
theArray[topOfStack--] = null;
* Return and remove most recently inserted item form the stack.
* @return most recently inserted item, or null, if stack is empty.
public Object TopAndPop() {
Object topItem = Top();
return topItem;
}
異常類
/**
* Exception class for access in full containers such as stacks, queues, and
* priority queues.
*/
public class Overflow extends Exception {
本文轉自冬冬部落格園部落格,原文連結:http://www.cnblogs.com/yuandong/archive/2006/08/23/484641.html,如需轉載請自行聯系原作者