Acwing_20 用两个栈实现队列

Acwing_20 用两个栈实现队列

用栈实现一个队列,支持如下四种操作:

	 - push(x) – 将元素x插到队尾;
	 - pop() – 将队首的元素弹出,并返回该元素;
	 - peek() – 返回队首元素;
	 - empty() – 返回队列是否为空;

	**栈的特点是先进后出,队列的特点是先进先出**
注意:

1、stackPush栈往stackPop栈中压入数据时,要一次性全部压入
2、如果stackPop栈中不为空,则不能向stackPop栈中压入数据

代码如下:
public class MyQueue {
    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.push(1);
        queue.push(2);
        queue.push(3);
        
        int temp1 = queue.pop();
        int temp2 = queue.peek();
        boolean temp3 = queue.empty();
        System.out.println(temp1);
        System.out.println(temp2);
        System.out.println(temp3);
    }

    public Stack<Integer> stackPush;    //压入栈
    public Stack<Integer> stackPop;     //弹出栈
    //栈的初始化操作
    public MyQueue(){
        stackPush = new Stack<Integer>();
        stackPop = new Stack<Integer>();
    }
    //入栈
    public void push(int value){
        stackPush.push(value);
    }
    //出栈
    public int pop(){
        if (!stackPush.empty()){
            while (!stackPush.empty()){
                stackPop.push(stackPush.pop());
            }
            return stackPop.pop();
        }else {
            throw new RuntimeException("Queue is empty!");
        }
    }
    //获取队首元素
    public int peek(){
        if (stackPop.empty()){
            throw new RuntimeException("Queue is empty!");
        }else {
            return stackPop.peek();
        }
    }
    //判断队列是否为空
    public boolean empty(){
        if (stackPop.empty()){
            return true;
        }else {
            return false;
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值