用数组实现Stack

2017-11-26  本文已影响0人  DeppWang

在一些面试题中,常常出现用数组实现Stack,主要实现它的push()/push()/pop()方法。也可以用容器(List)和链表实现,可以看这篇博文。以下是使用数组实现Stack:


public class StackTest {

    public static void main(String[] args) {

        ArrayStack stack = new ArrayStack(10);
        System.out.println("isEmpty: " + stack.isEmpty());
        for (int i = 0; i < 10; i++) {
            stack.push(i);
        }
        System.out.println("isFull: " + stack.isFull());
        System.out.println("thePeek: " + stack.peek());

        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }

}

class ArrayStack {
    private int[] array;
    private static int top;//相当于栈顶指针

    public ArrayStack(int size) {
        array = new int[size];
        top = -1;
    }

    boolean isEmpty() {
        return top == -1;
    }

    boolean isFull() {
        return array.length - 1 == top;
    }

    //入栈
    void push(int element) {
        if (isFull()) {
            System.out.println("栈已满");
        }
        array[++top] = element;//注意此处是++top
    }

    //弹栈
    int pop() {
        if (isEmpty()) {
            System.out.println("栈为空");
        }
        return array[top--];
    }

    //查看栈顶元素
    int peek() {
        return array[top];
    }
}

上一篇下一篇

猜你喜欢

热点阅读