package com.zengwen.stack;
/**
* 数组模拟栈
*/
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(5);
System.out.println("入栈~");
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(3);
arrayStack.push(4);
arrayStack.push(5);
System.out.println("遍历栈~");
arrayStack.list();
System.out.println("出栈~");
int pop = arrayStack.pop();
System.out.println(pop);
System.out.println("遍历栈~");
arrayStack.list();
}
}
//定义一个ArrayStack表示栈
class ArrayStack{
private int maxSize; // 栈的大小
private int[] stack; // 数组,数组模拟栈,数据就放在该数组
private int top = -1; // top表示栈顶,初始化为-1
//构造器
public ArrayStack(int maxSize){
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
//栈满
public boolean isFull(){
return top == maxSize - 1;
}
//栈空
public boolean isEmpty(){
return top == -1;
}
//入栈
public void push(int value){
if (isFull()){
System.out.println("栈满~~");
return;
}
// top++;
// stack[top] = value;
stack[++top] = value;
}
//出栈
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈空~~");
}
// int value = stack[top];
// top--;
// return value;
return stack[top--];
}
//遍历栈[遍历时需要从栈顶开始显示数据]
public void list(){
if (isEmpty()){
System.out.println("栈空~");
return;
}
for (int i = top; i >= 0; i--) {
System.out.println("stack[" + i + "]=" + stack[i]);
}
}
}