堆栈的数组实现

来源:互联网 发布:淘宝展现词怎么刷 编辑:程序博客网 时间:2024/05/16 07:24

用数组来模拟堆栈的各种运算操作

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** *  *//** * @author Administrator *新浪微博:ouc大飞 */public class Stack {    /**     * @param args     * @throws IOException      * @throws NumberFormatException      */    public static void main(String[] args) throws NumberFormatException, IOException {        // TODO Auto-generated method stub        BufferedReader buf;        int value;        StackByArray stack=new  StackByArray(10);        buf=new  BufferedReader(new InputStreamReader(System.in));        System.out.println("输入10个数字:");        for(int i=0;i<10;i++){            value=Integer.parseInt(buf.readLine());            stack.push(value);        }        System.out.println("============");        while(!stack.empty()){            System.out.println("堆栈弹出的顺序为:"+stack.pop());        }    }}class StackByArray{//以数组模拟堆栈的类声明    private int stack[]; //在类中声明数组    private int top;//指向堆栈顶端的索引    public StackByArray(int stack_size){        stack=new int[stack_size];//建立索引        top=-1;    }    //类方法push    public boolean push(int data){        if(top>=stack.length){//判断堆栈顶端索引是否大于数组长度            System.out.println("堆栈已满,无法再加入");            return false;        }else {            stack[++top]=data;//将数据存入堆栈            return true;        }    }    //类方法empty    public boolean empty(){        if(top==-1)            return true;        else            return false;    }    //类方法pop    //从堆栈中取出数据    public int pop(){        if(empty())            return -1;        else             return stack[top--];    }}
0 0
原创粉丝点击