集册 Java实例教程 为int值创建堆栈

为int值创建堆栈

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

536
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
为int值创建堆栈

public class StackOfInts {

/*来自 
 n  o  w  j  a  v  a . c o m*/

    private int[] stack;

    private int next = 0; // index of last item in stack + 1


    public StackOfInts(int size) {

        //create an array large enough to hold the stack

        stack = new int[size];

    }


    public void push(int on) {

        if (next < stack.length)

            stack[next++] = on;

    }


    public boolean isEmpty() {

        return (next == 0);

    }


    public int pop() {

        if (!isEmpty())

            return stack[--next]; // top item on stack/* from 时 代 J     a    v  a - nowjava.com*/

        else

            return 0;

    }


    public int getStackSize() {

        return next;

    }


    private class StepThrough {

        // start stepping through at i=0

        private int i = 0;


        // increment index

        public void increment() {

            if (i < stack.length)

                i++;

        }


        // retrieve current element

        public int current() {

            return stack[i];

        }


        // last element on stack?

        public boolean isLast() {

            if (i == getStackSize() - 1)

                return true;

            else

                return false;

        }

    }


    public StepThrough stepThrough() {

        return new StepThrough();

    }


    public static void main(String[] args) {


        // instantiate outer class as "stackOne"

        StackOfInts stackOne = new StackOfInts(15);


        // populate stackOne

        for (int j = 0; j < 15; j++) {

            stackOne.push(2 * j);

        }


        // instantiate inner class as "iterator"

        StepThrough iterator = stackOne.stepThrough();


        // print out stackOne[i], one per line

        while (!iterator.isLast()) {

            System.out.print(iterator.current() + " ");

            iterator.increment();

        }

        System.out.println();


    }


}


展开阅读全文