LEETCODE-Implement Queue using Stacks
2015-10-10 15:36
567 查看
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).
• 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 Queue { public: stack<int> in; stack<int> out; // Push element x to the back of queue. void push(int x) { in.push(x); } // Removes the element from in front of queue. void pop(void) { if(out.empty()) { while(!in.empty()) { int x = in.top(); in.pop(); out.push(x); } } // if(!out.empty()) out.pop(); } // Get the front element. int peek(void) { if(out.empty()) { while(!in.empty()) { int x = in.top(); in.pop(); out.push(x); } } // if(!out.empty()) return out.top(); } // Return whether the queue is empty. bool empty(void) { return out.empty() && in.empty(); } };
相关文章推荐
- UIView 动画
- 王立平-NGUI
- Java 中StringBuffer与StringBuilder区别(转)及String类的一些基本操作代码
- URAL 1910 Titan Ruins: Hidden Entrance
- UILable , Button
- request_irq() | 注册中断服务参考
- read PSE TPS2384 POE Firmware Guide
- 转:QT如何将.UI文件转成.h或.cpp文件
- UIView 的 属 性
- UILabel 属性祥记
- UIImage编码成Base64后上传,服务器端解码出错
- I.MX6 Manufacturing Tool V2 (MFGTool2) Update Command List (UCL) User Guide translate
- UITableView绑定不同的cell 的 ID 写法
- ios UITextField 设置默认提示
- hdu 5288 OO’s Sequence
- CEGUI-----动画
- 【Java GUI】Java GUI基金会
- 怪异模式(Quirks Mode)对 HTML 页面的影响
- apue第三章文件I/O
- Invalid ADAPTORNAME specified. Type 'imaqhwinfo' for a list of available ADAPTORNAMEs. Image acquisi