直接上代码了
package com.leolee.dataStructure.stack;
/**
* @ClassName ArrayStack
* @Description: 数组模拟栈
* @Author LeoLee
* @Date 2020/9/15
* @Version V1.0
**/
public class ArrayStack {
private int maxSize;
private int[] stack;//数组来模拟栈
private int top = -1;//栈顶,初始化为-1
public ArrayStack (int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
//栈满
public boolean isFull () {
return top == (maxSize - 1);
}
//栈空
public boolean isEmpty () {
return top == -1;
}
//入栈
public void push (int value) {
if (isFull()) {
System.out.println("stack is full");
return;
}
top++;
stack[top] = value;
}
//出栈
public int pop () {
if (isEmpty()) {
throw new NullPointerException("stack is empty");
}
int topValue = stack[top];
top--;
return topValue;
}
//由于栈先进后出的原则,由数组的末尾开始遍历
public void showData () {
if (isEmpty()) {
System.out.println("stack is empty");
return;
}
for (int i = top; i >= 0 ; i--) {
System.out.printf("stack[%d]:%d\n", i, stack[i]);
}
}
}
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(4);
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(3);
arrayStack.push(4);
arrayStack.showData();
System.out.println("-----------------------------");
arrayStack.pop();
arrayStack.pop();
arrayStack.showData();
}