直接上代码:
class ArrayStack{
//用数组模拟栈
int maxSize;
int[] stack;
int top = -1;//表示栈顶
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[maxSize];
}
//1, 入栈
public void pushStack(int value){
//判断是否满
if(IsFull()){
System.out.println("栈满了,不能添加");
return;
}
top++;
stack[top] = value;
}
//2, 出栈
public int popStack() throws Exception {
if(IsEmpty()){
throw new Exception("栈为空,不能出栈");
}
int value = stack[top];
top--;
return value;
}
//3. 栈的遍历
public void show(){
if(stack.length == 0){
System.out.println("栈空,不能遍历");
return;
}
for (int i = top; i >= 0; i--) {
System.out.println(stack[i]);
}
}
private boolean IsFull() {
return top == maxSize-1;
}
private boolean IsEmpty(){
return top == -1;
}
}
测试代码:
public static void main(String[] args) throws Exception {
ArrayStack stack = new ArrayStack(4);
stack.pushStack(1);
stack.pushStack(2);
stack.pushStack(3);
stack.pushStack(4);
stack.show();//4-3-2-1 先进后出
System.out.println("========");
stack.popStack();
stack.show();//3-2-1
}
测试结果:
原文:https://www.cnblogs.com/lvcai/p/13021835.html