模拟栈数据结构改进版(使用异常)
生活随笔
收集整理的這篇文章主要介紹了
模拟栈数据结构改进版(使用异常)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼
/*第一題:編寫程序,使用一維數組,模擬棧數據結構。要求:1、這個棧可以存儲java中的任何引用類型的數據。2、在棧中提供push方法模擬壓棧。(棧滿了,要有提示信息。)3、在棧中提供pop方法模擬彈棧。(棧空了,也有有提示信息。)4、編寫測試程序,new棧對象,調用push pop方法來模擬壓棧彈棧的動作。 */ package com.bjpowernode.javase.day23homework;public class Homework1 {public static void main(String[] args) {MyStack myStack = new MyStack();//壓棧try {myStack.push(new A());myStack.push(new A());myStack.push(new A());} catch (StackException e) {e.printStackTrace();}try {myStack.pop();myStack.pop();myStack.pop();} catch (StackException e) {e.printStackTrace();}} } class A{} class B{} class C{}class MyStack{//定義object數組,提供空間壓棧彈棧private Object[] objects;//棧幀,永遠指向棧頂元素,初始情況object數組沒有元素,棧幀指向-1private int index = -1;//poppublic Object pop() throws StackException {//判斷棧空否if (index < 0){throw new StackException("棧已空,彈棧失敗!");}else{//返回當前元素后,棧幀所指元素進行減一操作System.out.println("彈棧成功," + objects[index]);return objects[index--];}}//pushpublic void push(Object obj)throws StackException{if (index >= objects.length-1){throw new StackException("棧已滿,彈棧失敗!");}else{//壓棧,將引用類型數據壓入棧中this.objects[++index] = obj;System.out.println("壓棧成功," + obj);}}//constructorpublic MyStack() {//初始默認棧空間為2this(new Object[2]);}public MyStack(Object[] objects) {this.objects = objects;}//setter and getterpublic Object[] getObjects() {return objects;}public void setObjects(Object[] objects) {this.objects = objects;}public int getIndex() {return index;}public void setIndex(int index) {this.index = index;} } package com.bjpowernode.javase.day23homework;public class StackException extends Exception{public StackException() {}public StackException(String message) {super(message);} } 新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的模拟栈数据结构改进版(使用异常)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 协作难在何处
- 下一篇: 严格匹配_2020湖北省考招录“刚柔并济