//栈:后进先出结构;
public class MyStack <E>{
//声明一个数组来存储数据
private Object stack[] =null;
//声明栈顶
private int top=-1;
//记录栈的容量
private int size;
//构造方法初始化
public MyStack(int size) {
this.size =size;
this.stack= new Object[size];
}
//判断栈空
public boolean isEmpty(){
return top==-1;
}
//判断栈满
public boolean isFull(){
return top==size-1;
}
//入栈
public void push(E value) throws RuntimeException {
//判断 空间是否已满
if(isFull()){
//抛一个异常
throw new RuntimeException("栈已满");
}
//若栈未满则压栈
stack[++top]=value;
}
//出栈(只能从栈顶一个一个的出栈)
public E pop( )throws RuntimeException{
//判断是否栈空
if(isEmpty()){
throw new RuntimeException("栈为空");
}
//栈不为空则弹栈
Object object = stack[top--];
return (E)object;
}
@Override
public String toString(){
return Arrays.toString(stack);
}
public static void main(String[] args) {
MyStack <String> myStack =new MyStack<>(5);
myStack.push("this");
myStack.push("is");
myStack.push("a");
myStack.push("stack");
myStack.push("java");
System.out.println(myStack);//this is a stack
System.out.println(myStack.pop());//java
System.out.println(myStack.pop());//stack
System.out.println(myStack.pop());//a
System.out.println(myStack.pop());//is
System.out.println(myStack.pop());//this
}
}
java用数组模拟栈
于 2023-06-30 19:33:09 首次发布