232. Implement Queue using Stacks
来源:互联网 发布:网络培训机构 编辑:程序博客网 时间:2024/04/19 06:53
题目
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.
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis 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).
只能用栈的基本操作来模拟队列的基本操作,定义两个栈a和b,其中a保存队列的正序,在进队时使用;b保存队列的倒序,在出队时使用。
class Queue {private: stack<int> a,b;//压入时用a,弹出时用bpublic:// Push element x to the back of queue.void push(int x) { if (b.empty()) a.push(x);//b为空时证明没有pop过,直接在a中压入x else { while (!b.empty()){//如果队列进行过pop操作,则b保存的是pop之后的队列,是队列倒序 a.push(b.top());//因此a在压入新元素的时候先将b压入a,在a中形成正序队列,再压入x b.pop(); } a.push(x); }}// Removes the element from in front of queue.void pop(void) { if (a.empty()) b.pop();//a为空证明没有再压入新元素,b已经是队列倒序,可以直接弹出 else{ while(!a.empty()){//否则b保存a的倒序结果,然后弹出 b.push(a.top()); a.pop(); } b.pop(); }}// Get the front element.int peek(void) { if (a.empty()) return b.top();//a为空则与pop一样返回b的首元素 else { while(!a.empty()){//否则b保存a的倒序结果,然后弹出b的首元素 b.push(a.top()); a.pop(); } return b.top(); }}// Return whether the queue is empty.bool empty(void) { return a.empty()&&b.empty();}};
0 0
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks
- xml或者代码实现Animation
- python-django-permission
- HDOJ 2052 Picture
- sga pga uga分配情况分析
- [poj 1019] Number Sequence 数学 想法题
- 232. Implement Queue using Stacks
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片的优缺点比较
- OpenCV 2.x/3.x 随机初始化矩阵
- String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有?
- 防止打包的时候删除SDK需要的so库
- iOS开发-环信UI集成
- 五个最佳案例带你解读Node.js的前后之道
- 新装LINUX系统如何获得ROOT权限
- Android自定义spinner下拉框实现的实现