结果
image.png
完整测试代码
package com.nan;
/**
* @author klr
* @create 2020-07-03-19:06
*/
public class ArrayStack {
private int top = -1;//top标识栈顶,初始化为-1
private int maxSize;//栈的大小
private int[] stack;//栈
public static void main(String[] args) throws Exception {
ArrayStack arrayStack = new ArrayStack(4);
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(4);
System.out.println("入栈1/2/4:");
arrayStack.list();
System.out.println("出栈2个:");
System.out.println(arrayStack.pop());
System.out.println(arrayStack.pop());
arrayStack.list();
}
public ArrayStack(int size) {
maxSize = size;
stack = new int[maxSize];
}
//判断栈是否已满
public boolean isFull() {
if (top == maxSize - 1) {
return true;
}
return false;
}
//判断栈是否为空
public boolean isEmpty() {
if (top == -1) {
return true;
}
return false;
}
//元素入栈
public void push(int value) {
if (isFull()) {
System.out.println(("栈已满,无法添加"));
return;
}
stack[++top] = value;
}
//元素出栈
public int pop() throws Exception {
if (isEmpty()) {
throw new Exception("栈已空,无法出栈");
}
return stack[top--];
}
//展示栈
public void list() {
if (isEmpty()) {
System.out.println("栈全空");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
}
网友评论