java-模拟出栈入栈
生活随笔
收集整理的這篇文章主要介紹了
java-模拟出栈入栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.sc;class stack{int array[]=new int[20]; //定義棧的存儲結構,數組后期會進行擴容int size=0;//棧中存放數據的個數/*** * push()函數用來進行入棧操作 無返回值 */public void push(int num){if(size>=array.length){//判斷入棧個數是否超過存儲結構的最大值//進行數組擴充int array_new []=new int [array.length*2];//array中的數據全部copy到array_mew中System.arraycopy(array, 0, array_new, 0, array.length);array=array_new;}else{array[size++]=num;}}/*** pop()函數用來進行出棧操作 返回的出棧之前的棧頂元素*/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());}}
總結
以上是生活随笔為你收集整理的java-模拟出栈入栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 组合数NYOJ
- 下一篇: java-模拟存放String类型数据的