Implement Queue by Two Stacks 解题报告

Implement Queue by Two Stacks

Description

As the title described, you should only use two stacks to implement a queue’s actions.

The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Example

push(1)
pop()     // return 1
push(2)
push(3)
top()     // return 2
pop()     // return 2

实现思路

  1. 设有两个栈A和栈B,每次添加新元素时,都放入栈A中,每次需要从数据结构中取元素,都从栈B中取。
  2. 一旦栈中没有可取元素了,就将A中所有元素压入栈B中,假设元素压入栈A顺序是:1,2,3,4,5,从左到右对应先后次序,如果从栈A中取出,则是5,4,3,2,1(即先取5,最后取1),然后再放入栈B中,则在栈B中的元素顺序为5,4,3,2,1,再从栈B取出元素,则后进先出,即依次取出1,2,3,4,5,从而总体形成了一个(1)先进(1)先出的队列顺序。
public class MyQueue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    private Stack<Integer> curStack;

    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void push(int element) {
        stack1.push(element);
    }

    public int pop() {
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    public int top() {
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.peek();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值