[232] Implement Queue using Stacks

1. 题目描述

Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

使用栈实现队列。只能使用栈提供的push, peek/pop, size和empty方法。

2. 解题思路

栈和队列不同的地方在于,栈为后进先出,而队列为先进先出。也就是说,对于一个栈,只能看到当前栈顶的元素,但是对于队列,我们要看到位于当前栈中最深处的元素。但是当我们把一个栈翻转过来,栈中最深处的元素就变成了当前栈顶元素,再顺序出栈就能达到队列的效果。所以想法就是使用两个栈,一个栈保存正序列元素,另一个栈用来翻转这些元素。入队操作只需要push到正序列元素中,出队操作则先将正序列元素进行反转,再输出最上面的元素即可。值得一提的是,当前翻转过的栈不为空时,如果将正序列翻转后push进来就打乱了原有栈的顺序,所以需要加一个判断,当当前翻转栈有元素时直接出队即可。
双栈队列

3. Code

import java.util.Stack;

class MyQueue {
    Stack<Integer> forwardStack = new Stack<>();
    Stack<Integer> reverseStack = new Stack<>();

    // Push element x to the back of queue.
    public void push(int x) {
        forwardStack.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        if(reverseStack.empty())
            doReverse();
        reverseStack.pop();
    }

    // Get the front element.
    public int peek() {
        if(reverseStack.empty())
            doReverse();
        return reverseStack.peek();
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return forwardStack.size() == 0 && reverseStack.size() == 0;
    }

    /**
     * 翻转栈
     */
    private void doReverse()
    {
        while(!forwardStack.empty())
        {
            reverseStack.push(forwardStack.pop());
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值