力扣225. 用队列实现栈

Problem: 225. 用队列实现栈

题目描述:

在这里插入图片描述在这里插入图片描述

思路

1.对一个queue模拟栈的操作,同时用一个int类型的变量topElem记录每次每次队列队尾的元素(也即是模拟stack中的stack的栈顶元素);
2.void push(int x):直接将元素入队,同时用topElem记录该元素;
3.int pop():先将队尾倒数两个元素前的元素出队再入队,再将topElem更新记录尾当前队列的队头元素,再将当前的对头元素出队、入队,最后将当前的对头元素出队返回
4.int top():直接返回topElem即可
5.boolean empty():直接判断队列是否位空即可

Code

class MyStack {
    Queue<Integer> queue;
    int topElem;

    public MyStack() {
        queue = new LinkedList<>();
        topElem = 0;
    }

    /**
     * Push the element to the queue
     *
     * @param x The element to be pushed
     */
    public void push(int x) {
        queue.offer(x);
        topElem = x;
    }

    /**
     * Remove the top element of stack
     *
     * @return int
     */
    public int pop() {
        int size = queue.size();
        //remain tow tail element of queue
        while (size > 2) {
            queue.offer(queue.poll());
            size--;
        }
        //recode the new tail element
        topElem = queue.peek();
        queue.offer(queue.poll());
        return queue.poll();
    }

    /**
     * Return the tail element of queue
     *
     * @return int
     */
    public int top() {
        return topElem;
    }

    /**
     * Check the empty
     *
     * @return boolean
     */
    public boolean empty() {
        return queue.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值