2、由两个栈组成队列

题目

编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)。

解法

一个栈作为入队栈,另一个栈作为出队栈。经过两个栈的传递操作可以实现先进先出,满足队列的要求。

import java.util.Stack;

public class twoStackToQueue {
    private Stack<Integer> pushStack;
    private Stack<Integer> popStack;

    public twoStackToQueue() {
        this.pushStack = new Stack<Integer>();
        this.popStack = new Stack<Integer>();
    }

    // 入队直接到入队栈就行
    public void add(Integer newNum){
        this.pushStack.push(newNum);
    }

    // 出队需要进行判断,当两个栈空时抛出队列空的异常
    // 另外分为两种情况:
    // 当popStack里面有元素时,popStack出栈即为出队;
    // 当popStack里面没有元素时,需要将pushStack的元素全部导入popStack,然后popStack出栈即为出队
    public Integer poll(){
        if(this.pushStack.isEmpty() && this.popStack.isEmpty()){
            throw new RuntimeException("Your queue is empty!");
        }else if(popStack.isEmpty()){
            while(!this.pushStack.isEmpty()){
                this.popStack.push(this.pushStack.pop());
            }
        }
        return this.popStack.pop();
    }

    //同poll,但是不进行pop操作,使用peek操作
    public Integer peek(){
        if(this.pushStack.isEmpty() && this.popStack.isEmpty()){
            throw new RuntimeException("Your queue is empty!");
        }else if(this.popStack.isEmpty()){
            while(!this.pushStack.isEmpty()){
                this.popStack.push(this.pushStack.pop());
            }
        }
        return this.popStack.peek();
    }
}

在这里插入图片描述

测试

import twoStackToQueue.twoStackToQueue;

public class twoStackToQueueTest {
    public static void main(String[] args) {
        twoStackToQueue a = new twoStackToQueue();
        a.add(1);
        a.add(2);
        a.add(3);
        System.out.println(a.poll());
        a.add(4);
        a.add(5);
        System.out.println(a.poll());
        System.out.println(a.poll());
        System.out.println(a.poll());
        a.add(6);
        System.out.println(a.peek());
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值