博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]--232. Implement Queue using Stacks
阅读量:7039 次
发布时间:2019-06-28

本文共 1586 字,大约阅读时间需要 5 分钟。

Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.

pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

跟前面用队列实现堆原理是差不多的。

class MyQueue {        Stack
s1 = new Stack
(); Stack
s2 = new Stack
(); // Push element x to the back of queue. public void push(int x) { s1.push(x); } // Removes the element from in front of queue. public void pop() { while (s1.size() > 1) s2.push(s1.pop()); s1.pop(); while (s2.size() > 0) s1.push(s2.pop()); } // Get the front element. public int peek() { while (s1.size() > 0) s2.push(s1.pop()); int n = s2.peek(); while (s2.size() > 0) s1.push(s2.pop()); return n; } // Return whether the queue is empty. public boolean empty() { return s1.isEmpty(); } }

转载地址:http://ixaal.baihongyu.com/

你可能感兴趣的文章
事故现场:MySQL 中一个双引号的错位引发的血案 ...
查看>>
MaxCompute_UDF_开发指南
查看>>
云MSP服务案例丨某知名制造集团的Oracle RAC部署实践 ...
查看>>
如何基于ReplayKit实现低延迟rtmp推屏
查看>>
说说JSON和JSONP,也许你会豁然开朗
查看>>
没有所谓好与不好,只是能否适用和用的好
查看>>
程序员写简历时必须注意的技术词汇拼写(持续更新...)
查看>>
ams光学传感器助力小米手机创新发展
查看>>
Python 特色介绍
查看>>
JavaScript_知识点梳理note1
查看>>
PostgreSQL 开启with-llvm(JIT)后,新增插件异常(clang: Command not found)处理
查看>>
思考设计SQL优化方案
查看>>
tomcat 调优-生产环境必备
查看>>
浅析C++的引用与const指针与各种传递方式
查看>>
Java并发编程75道面试题及答案
查看>>
仓储+调度,YOGO智能配送站能否改变外卖配送格局?
查看>>
jQuery-easyui和validate表单验证实例
查看>>
【对讲机的那点事】5G时代的到来,2G和3G将会被关停?
查看>>
DeepLearning.ai学习笔记(二)改善深层神经网络:超参数调试、正则化以及优化--week3 超参数调试、Batch正则化和程序框架...
查看>>
NSMutableArray 简单细说
查看>>