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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值