天天看點

stack(棧)的簡單數組實作

棧特點先進後出

下面用java實作一個簡單的棧

import java.util.Scanner;

/**
 * @Author: taoqianlilang
 * @Description:
 * @Date: Created in 11:09 2020/4/7
 * @Modified By:
 */
public class ArrayStackDemo {
    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        boolean loop=true;

        String key="";

        ArrayStack stack=new ArrayStack(4);

        while (loop){
            System.out.println("show  :顯示棧的順序");
            System.out.println("exit  :退出程式");
            System.out.println("push  :入棧");
            System.out.println("pop   :出棧");
            System.out.println("輸入你的選擇");
            key=sc.nextLine();
            switch (key){
                case "show":
                    stack.list();
                    break;
                case "exit":
                    sc.close();
                    loop=false;
                    break;
                case "push":
                    System.out.println("輸入需要入棧的數字");
                    int value = sc.nextInt();
                    sc.nextLine();
                    stack.push(value);
                    break;
                case "pop":
                    System.out.println("彈出的内容為");
                    System.out.println(stack.pop());
                    break;
                default:
                    break;
            }
         }
        System.out.println("程式退出");


    }
}

class ArrayStack{

    private int maxSize;
    private int[] stack;
    private int top=-1;

    /**
     * @param maxSize 棧最大容量
     */
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack=new int[maxSize];
    }

    //判斷棧滿

    public boolean isFull(){
        if (top==maxSize-1){
            System.out.println("棧滿");
            return true;
        }
        return false;
    }
    public boolean isEmpty(){
        if (top==-1){
            System.out.println("棧空");
            return true;
        }
        return false;
    }
    public void push(int value){
        if (isFull()){
            return;
        }
        top++;
        stack[top]=value;
    }
    public int pop(){
        if (isEmpty()){
            return -1;
        }
        int value=stack[top];
        top--;
        return value;
    }

    /**
     * 顯示棧的情況
     */
    public void list(){
        if (isEmpty()){
            System.out.println("棧空");
        }

        for (int i=top;i>=0;i--){
            System.out.println("棧号為 :"+i+"值為 :"+stack[i]);
        }
    }
}