集册 Java实例教程 基于int数组创建堆栈

基于int数组创建堆栈

欢马劈雪     最近更新时间:2020-01-02 10:19:05

519
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
基于int数组创建堆栈

class Stacks

{

    private int[] array;
    /** from 
    N o  w  J a v a . c o m - 时  代  Java**/

    private int tos;

    private int size;


    public Stacks()

    {

        size = 10;

        array = new int[size];

        tos = -1;

    }


    public Stacks(int size)

    {

        this.size = size;

        array = new int[size];

        tos = -1;
        /*来自 
         NowJava.com - 时代Java*/

    }


    public void push(int value)

    {

        if(tos == size - 1)

            System.out.println("Stack is full");

        else

            array[++tos] = value;

    }


    public void pop()

    {

        if(tos == -1)

            System.out.println("Stack is empty");

        else

            --tos;

    }


    public void traverse()

    {

        int temp = tos - 1;


        if(tos == -1)

            System.out.println("Stack is empty");

        else

        {

            System.out.println("Top of stack is : " + array[tos]);


            if(temp > -1)

                System.out.print("Other : ");


            while(temp > -1)

                System.out.print(array[temp--] + " ");


            System.out.println();

        }

    }


    public static 
展开阅读全文