数据结构 - 栈(数组模拟栈操作)
生活随笔
收集整理的這篇文章主要介紹了
数据结构 - 栈(数组模拟栈操作)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
數(shù)組模擬棧操作
package stack;import java.util.Scanner;public class ArrayStackDemo {public static void main(String[] args) {//測試ArrayStack//創(chuàng)建棧ArrayStack arrayStack = new ArrayStack(4);String key = "";boolean loop = true;Scanner sc = new Scanner(System.in);while (loop){System.out.println("show:表示顯示棧");System.out.println("exit:退出程序");System.out.println("push:表示入棧");System.out.println("pop:表示出棧");key = sc.next();switch (key){case "show":arrayStack.list();break;case "push":System.out.println("請輸入一個數(shù)");int value = sc.nextInt();arrayStack.push(value);break;case "pop":try{System.out.println("出棧的數(shù)據(jù)是:"+arrayStack.pop());}catch (Exception e){System.out.println(e.getMessage());}break;case "exit":sc.close();loop = false;break;}}System.out.println("程序退出");} }class ArrayStack{private int maxSize; //棧大小private int[] stack;//數(shù)組模擬棧,數(shù)據(jù)放入數(shù)組里private int top = -1; //top表示棧頂,初始化為-1//構(gòu)造器public ArrayStack(int maxSize) {this.maxSize = maxSize;stack = new int[this.maxSize];}//棧滿public boolean isFull(){return top == maxSize - 1;}//???/span>public boolean isEmpty(){return top == -1;}// 入棧 pushpublic void push(int value){//判斷棧是否滿if (isFull()){System.out.println("棧滿,不能入棧");return;}top++;stack[top] = value;}//出棧public int pop(){if (isEmpty()){//拋出異常throw new RuntimeException("棧空");}int value = stack[top];top--;return stack[value];}//遍歷棧(從棧頂開始)public void list(){if (isEmpty()){System.out.println("???#34;);}for (int i = top; i>=0; i--){System.out.printf("stack[%d] = %d\n",i,stack[i]);}} }總結(jié)
以上是生活随笔為你收集整理的数据结构 - 栈(数组模拟栈操作)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米13或提前亮相 第二代骁龙8发布时间
- 下一篇: 【Python 标准库学习】时间相关的函