Implement Stack

题目:

Implement a stack. You can use any data structure inside a stack except stack itself to implement it.

分析:

注意当empty的时候再pop或者top会有indexOutOfBoundException,这里没有处理,和stack这两个函数本身基本保持一致了,不过stack的函数本身是emptyStackException

解法:

class Stack {
    // Push a new item into the stack
    List<Integer> stack = new ArrayList<Integer>();
    public void push(int x) {
        // Write your code here
        stack.add(x);
    }

    // Pop the top of the stack
    public void pop() {
        // Write your code here
        stack.remove(stack.size() - 1);
    }

    // Return the top of the stack
    public int top() {
        // Write your code here
        return stack.get(stack.size() - 1);
    }

    // Check the stack is empty or not.
    public boolean isEmpty() {
        // Write your code here
        return stack.size() == 0;
    }    
}

results matching ""

    No results matching ""