/**
* @author ymy
* @date 2020/5/11
*
* 使用数组模拟栈
*/
public class SeqStack {
private int maxSize;//栈的容量
private int top;//栈顶
private Object [] data;//用来存放数据的区域
public SeqStack(int maxSize){
top=-1;
this.maxSize=maxSize;
data=new Object[maxSize];
}
public void push(Object obj){
if (isFull()){
System.out.println("栈已满");
return;
}
data[++top]=obj;
}
public Object pop(){
if (isEmpty()){
throw new RuntimeException("栈为空");
}
return data[top--];
}
public boolean isEmpty(){
return top==-1;
}
public boolean isFull(){
return top==maxSize-1;
}
}
测试代码:
/**
* @author ymy
* @date 2020/5/11
*/
public class TestStack {
public static void main(String[] args) {
SeqStack stack = new SeqStack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
while (!stack.isEmpty()){
System.out.println(stack.pop());
}
System.out.println("===========");
stack.push(6);
stack.push(7);
stack.push(8);
while (!stack.isEmpty()){
System.out.println(stack.pop());
}
}
}
运行结果:
原文:https://www.cnblogs.com/polary/p/12871343.html