package com.Stack;
public class ArrayStack <AnyType>{
public ArrayStack(){
theArray = (AnyType [])new Object[DEFAULT_CAPACITY];
topOfStack = -1;
};
public boolean isEmpty(){
return topOfStack == -1;
}
public void makeEmpty(){
topOfStack = -1;
}
public AnyType top(){
try {
if(isEmpty())
throw new Exception("ArrayStack top");
}
catch (Exception e) {
e.printStackTrace();
}
return theArray[topOfStack];
}
public void pop(){
if(isEmpty()){
//抛出异常
}
topOfStack--;
}
public AnyType topAndPop(){
if(isEmpty()){
//....
}
return theArray[topOfStack--];
// AnyType data = theArray[topOfStack];
// topOfStack--;
// return data;
}
public void push(AnyType x){
if(topOfStack+1 == theArray.length){
//doubleArray();
}
theArray[++topOfStack] = x;
}
/*
* 数组加倍
*/
private void doubleArray(){
}
private int topOfStack;
private AnyType[] theArray;
private static final int DEFAULT_CAPACITY = 10;
}
测试类:
package com.Stack;
public class testArrayStack {
@SuppressWarnings("unchecked")
public static void main(String[] args){
ArrayStack stack = new ArrayStack();
String[] data = new String[]{"a","b","c"};
for(int i = 0;i < data.length;i++){
stack.push(data[i]);
System.out.println(data[i]+" ");
}
System.out.println("*************************");
while(!stack.isEmpty()){
System.out.println(stack.topAndPop()+"");
}
}
}
输出结果:
a
b
c
*************************
c
b
a