栈是一个先入后出的有序数据结构(FILO)
栈的操作操作只能是在栈顶(Top)或者栈底(Bottom)进行
声明:下面的代码只是一个最基础的实现,没有经过严格的测试。
/**
* 使用数组模拟栈
*/
public class MyArrayStack<E> {
private int top=-1;
private int maxSize;
private Object[] arr;
public MyArrayStack(int maxSize) {
this.maxSize = maxSize;
arr=new Object[maxSize];
}
//判断栈是否已经满了
public boolean isFull(){
//top相当于数组的下标
return top==maxSize-1;
}
public boolean isEmpty(){
return top==-1;
}
//入栈
public void push(E e){
if(isFull()){
throw new RuntimeException("栈空间已满!");
}
top++;
arr[top]=e;
}
//出栈,每次只取栈顶的第一个元素
public E pop(){
if(isEmpty()){
throw new RuntimeException("栈为空!");
}
E e=(E)arr[top];
top--;
return e;
}
public void show(){
for (Object o : arr) {
System.out.println(o.toString());
}
}
public static void main(String[] args) {
MyArrayStack<String> myArrayStack = new MyArrayStack(5);
myArrayStack.push("110");
myArrayStack.push("220");
myArrayStack.push("330");
myArrayStack.push("440");
myArrayStack.push("550");
System.out.println(myArrayStack.pop());
System.out.println(myArrayStack.pop());
System.out.println(myArrayStack.pop());
System.out.println(myArrayStack.pop());
System.out.println(myArrayStack.pop());
}
}