由两个栈组成的队列

【题目】

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

package leif.algorithm_and_data_structure.stack_and_queue;

import java.util.Stack;

public class TwoStacksQueue {
    private Stack<Integer> stackPush = new Stack<Integer>();
    private Stack<Integer> stackPop = new Stack<Integer>();

    public void add(int pushInt) {
        stackPush.push(pushInt);
    }

    public int poll() {
        if (stackPop.isEmpty() && stackPush.isEmpty()) {
            throw new RuntimeException("Queue is empty!");
        } else if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }

        return stackPop.pop();
    }

    public int peek() {
        if (stackPop.isEmpty() && stackPush.isEmpty()) {
            throw new RuntimeException("Queue is empty!");
        } else if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }

        return stackPop.peek();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 题目 编写一个类,用两个栈实现队列,支持队列的基本操作(add, poll, peek) 要求 无 思路 使用两个...
    永志阅读 600评论 0 0
  • 题目一:设计一个带有getMin功能的栈 [leetcode155]https://leetcode.com/pr...
    futurehau阅读 576评论 0 0
  • 物流给妹妹打来电话,说是有个快递让她去取一下。 想了又想,我最近也没买什么东西呀?抱着好奇的疑问;妹妹开着自己的小...
    盼盼蜗牛漫步阅读 1,566评论 0 0
  • 阵雨初歇,出蓬门。潺潺涓流,横过道。一畦蓝天碧波涌,万里黄土面朝天。莫等闲,少年悲白发,空余叹! 笑侃当年居胥梦,...
    虎子的烟火阅读 888评论 0 1
  • 童心大发的想看一部动画片,这个画面感的确没有让人失望,可能自己心中也有一个气球的梦吧。前15分钟,卡尔和艾利的故事...
    不酷的我不喜欢阅读 340评论 0 0

友情链接更多精彩内容