【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;
    }
}

所有操作複雜度和普通棧一樣。

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