java-模拟出栈入栈
生活随笔
收集整理的這篇文章主要介紹了
java-模拟出栈入栈
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
package com.sc;class stack{int array[]=new int[20]; //定義棧的存儲(chǔ)結(jié)構(gòu),數(shù)組后期會(huì)進(jìn)行擴(kuò)容int size=0;//棧中存放數(shù)據(jù)的個(gè)數(shù)/*** * push()函數(shù)用來(lái)進(jìn)行入棧操作 無(wú)返回值 */public void push(int num){if(size>=array.length){//判斷入棧個(gè)數(shù)是否超過(guò)存儲(chǔ)結(jié)構(gòu)的最大值//進(jìn)行數(shù)組擴(kuò)充int array_new []=new int [array.length*2];//array中的數(shù)據(jù)全部copy到array_mew中System.arraycopy(array, 0, array_new, 0, array.length);array=array_new;}else{array[size++]=num;}}/*** pop()函數(shù)用來(lái)進(jìn)行出棧操作 返回的出棧之前的棧頂元素*/public int pop(){//判斷出棧是否越界try{return array[--size];}catch(Exception e){e.printStackTrace();return -1;}}
}public class ExampleOfStack {public static void main(String[] args) {// TODO Auto-generated method stubstack st=new stack();st.push(1);st.push(2);st.push(3);st.push(4);System.out.println(st.pop());System.out.println(st.pop());System.out.println(st.pop());System.out.println(st.pop());}}
總結(jié)
以上是生活随笔為你收集整理的java-模拟出栈入栈的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 组合数NYOJ
- 下一篇: java-模拟存放String类型数据的