【Lintcode】495. Implement Stack

题目地址:

https://www.lintcode.com/problem/implement-stack/description

实现栈。

可以用一个数组实现栈,另外用一个变量size来标记当前栈里元素个数。如果在push的时候size = stack.length了,则需要扩容,一般扩容成两倍。如果pop后size = stack.length / 4,则栈可以缩容成stack.length / 2以防复杂度震荡。代码如下:

public class Stack {
    
    int[] stack = new int[10];
    int size = 0;
    
    /*
     * @param x: An integer
     * @return: nothing
     */
    public void push(int x) {
        // write your code here
        if (size == stack.length) {
            resize(stack.length * 2);
        }
        
        stack[size++] = x;
    }
    
    /*
     * @return: nothing
     */
    public void pop() {
        // write your code here
        size--;
        if (size == stack.length / 4 && stack.length / 4 > 0) {
            resize(stack.length / 2);
        }
    }
    
    /*
     * @return: An integer
     */
    public int top() {
        // write your code here
        return stack[size - 1];
    }
    
    /*
     * @return: True if the stack is empty
     */
    public boolean isEmpty() {
        // write your code here
        return size == 0;
    }
    
    private void resize(int newCapacity) {
        int[] tmp = new int[newCapacity];
        for (int i = 0; i < size; i++) {
            tmp[i] = stack[i];
        }
        
        stack = tmp;
    }
}

所有操作复杂度和普通栈一样。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章