【java】实现【栈】

it2023-12-21  55

public class StackDemo {

    public static void main(String[] args) {

        Stack s = new Stack(5);         s.push(1);         s.push(2);         s.push(3);         s.push(4);         s.push(5);         s.showStack();     } }

class Stack{     //栈大小     private int maxSize;     private int top =-1;     private Object [] obj;          public Stack(int nums) {         this.maxSize = nums;         obj = new Object[this.maxSize];     }          //判断栈满     public boolean isFull() {         return top == maxSize-1;     }          //判断栈空     public boolean isEmpty() {         return top == -1;     }          //出栈     public Object pop() {         if(isEmpty()) {             throw new RuntimeException("栈空~~");         }         Object val = this.obj[top];         top--;         return val;     }          //入栈     public void push(Object obj) {         if(isFull()) {             System.out.println( "栈满~~" );              return;         }          top++;         this.obj[top] = obj;     }          //显示数据     public void showStack() {         System.out.println("======================================");         if(isEmpty()) {             System.out.println("空栈!没有数据~~~");             return;         }         while (top>=0) {             System.out.println(obj[top]);             top--;         }         System.out.println("======================================");     } }  

最新回复(0)