package com.zsx.structure.stack;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack arrayStack=new ArrayStack(10);
arrayStack.show();
arrayStack.pull(2);
arrayStack.pull(3);
arrayStack.pull(21);
arrayStack.pull(23);
arrayStack.pull(5);
arrayStack.pull(6);
arrayStack.pull(1);
arrayStack.pull(1);
arrayStack.pull(2);
arrayStack.pull(7);
arrayStack.pull(57);
arrayStack.show();
System.out.println(arrayStack.pop());
arrayStack.show();
}
}
class ArrayStack {
//大小
private int maxSize;
//数据
private int[] stack;
//栈顶
private int top = -1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
/**
* 判断满
*
* @return
*/
public boolean isFull() {
return top == maxSize - 1;
}
/**
* 判断空
*
* @return
*/
public boolean isEmpty() {
return top == -1;
}
public void pull(int data) {
if (this.isFull()) {
System.out.println("满了");
return;
}
top++;
stack[top] = data;
}
public int pop() {
if (this.isEmpty()) {
throw new RuntimeException("空");
}
int value = stack[top];
top--;
return value;
}
public void show() {
System.out.println("________________________");
if (!this.isEmpty()) {
for (int i = this.top; i >= 0; i--) {
System.out.println("第"+i+"个:"+this.stack[i]);
}
}
}
}
栈_数组模拟栈
最新推荐文章于 2024-07-23 17:01:37 发布