java-模拟出栈入栈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xllfy123/article/details/79602851
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 stub
        stack 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());
    }

}

猜你喜欢

转载自blog.csdn.net/xllfy123/article/details/79602851