LeetCode —— 【225. 用队列实现栈】

本来我是使用单链表实现的(queue)但是总是报超时,没办法我只能使用了双向链表deque

java

public class MyStack {

    /**
     * Initialize your data structure here.
     */
    private Deque<Integer> queue;
    ;

    public MyStack() {
//        向上转型
        queue = new LinkedList<Integer>();
    }

    /**
     * Push element x onto stack.
     */
    public void push(int x) {
        queue.offer(x);

    }

    /**
     * Removes the element on top of the stack and returns that element.
     */
    public int pop() {
//把queue里面的数据逐渐放入到help中,同时剩余一个在queue中, 之后把最后一个给删除就是pop了。

        if (!queue.isEmpty()) {
            int temp = queue.getLast();
            queue.removeLast();
            return temp;
        }
        else  throw new RuntimeException("error");


    }

    /**
     * Get the top element.
     */
    public int top() {
        return queue.getLast();
    }

    /**
     * Returns whether the stack is empty.
     */
    public boolean empty() {
        return queue.isEmpty();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值