栈是允许在同一端进行插入和删除操作的特殊线性表。允许进行插入和删除操作的一端称为栈顶(top),另一端为栈底(bottom);栈底固定,而栈顶浮动;栈中元素个数为零时称为空栈。插入一般称为进栈(PUSH),删除则称为退栈(POP)。 栈也称为先进后出表。
import java.util.Arrays;
/**
* <h2>Stack</h2>仿照java的 Stack类实现的
* <dl>
* <br>
* <dt>职能概要 <br>
* <dd> 用一个数组来模拟栈的操作,当栈已满时,把大小扩大为原来的二倍 <br>
* <dd>
* </dl>
*
* @author Bruce
* @date Sep 7, 2011
* @version 1.0
*/
class Stack<E> {
private Object[] elementData;
private int elementCount;
private static final int INITIAL_CAPACITY = 1;
public Stack() {
super();
elementData = new Object[INITIAL_CAPACITY];
elementCount = 0;
}
/**
* 入栈操作
* @param element
*/
public void push(E element) {
int oldCapacity = elementData.length;
int newCapacity;
if (elementCount + 1 > oldCapacity) {
newCapacity = oldCapacity * 2;
if (newCapacity < elementCount + 1) {
newCapacity = elementCount + 1;
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
elementData[elementCount++] = element;
}
/**
* 出栈操作,返回栈顶元素;并且将其移除栈
* @return object
*/
public Object pop() {
Object temp = elementData[elementCount - 1];
if (elementCount > 0) {
elementData = Arrays.copyOf(elementData, --elementCount);
}
return temp;
}
/**
* 返回栈顶元素
* @return
*/
public Object peek() {
if (elementCount > 0) {
return elementData[elementCount - 1];
} else
return null;
}
public boolean isEmpty() {
return elementCount == 0;
}
public Object[] getElementData() {
return elementData;
}
}
/**
* 测试类
* @author Bruce
* @date Sep 7, 2011
* @version
*/
public class SimulationStack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(4);
stack.push(0);
stack.push(1);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}