Implement Queue using Stacks

本文介绍了一种使用两个栈来实现队列的方法。通过将入队操作放置在一个栈中,并在需要出队时将该栈的数据倒置到另一个栈来完成。这种方式能够有效地模拟队列的先进先出特性。

题目链接

思路:
两个栈。当有输出的时候。如果B里有东西就pop.没有的话把所有A里面的东西拿出来放入B。所有的入队全部放在A里面。

import java.util.Stack;

class MyQueue {
    // Push element x to the back of queue.

    Stack<Integer> stackA=new Stack<Integer>();
    Stack<Integer> stackB=new Stack<Integer>();
    boolean isOut=true;


    public void push(int x) {
        stackA.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        if(stackB.isEmpty())
        {
            while(!stackA.isEmpty())
            {
                stackB.push(stackA.pop());
            }
        }
        stackB.pop();
    }

    // Get the front element.
    public int peek() {
          if(stackB.isEmpty())
          {
            while(!stackA.isEmpty())
            {
                stackB.push(stackA.pop());
            }
          }
          return stackB.peek();
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return stackA.isEmpty()&&stackB.isEmpty();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值