LeetCode:Implement Queue using Stacks
2015-08-12 10:48
489 查看
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
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 emptyoperations 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 { private: stack<int> stack1,stack2; public: // Push element x to the back of queue. void push(int x) { stack1.push(x); } // Removes the element from in front of queue. void pop(void) { if(stack2.empty()) { while(!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } stack2.pop(); } // Get the front element. int peek(void) { if(stack2.empty()) { while(!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } return stack2.top(); } // Return whether the queue is empty. bool empty(void) { if(stack1.empty()&&stack2.empty()) return true; else return false; } };
相关文章推荐
- xquery 除法 和节点个数
- 自己封装的Metro风格的后台UI框架,暂命名MUI(持续更新)
- iOS UITextView内容添加后,自动滚动到最后一行
- UICollectionView入门--使用系统UICollectionViewFlowLayout布局类
- LeetCode题解:Implement Queue using Stacks
- STL系列之一 deque双向队列
- 各种设备的CSS3 MediaQuery整理及爽歪歪写法
- HDU 3397 Sequence operation(线段树·成段更新·区间合并·混合操作)
- Android详细的对话框AlertDialog.Builder小示例
- EasyUI学习笔记8:MIS开发利器_ datagrid插件(下)(终结篇)
- EasyUI学习笔记7:MIS开发利器_ datagrid插件(中)
- 本地化下按首字母分组排序的神器——UILocalizedIndexedCollation
- EasyUI学习笔记6:MIS开发利器_ datagrid插件(上)
- EasyUI学习笔记5:来点甜点_ menu和theme插件
- EasyUI学习笔记4:展现内容_ tabs插件
- EasyUI学习笔记3:导航菜单_ accordion和tree插件
- leetcode_Repeated DNA Sequences
- Purpose of requirePermission attribute (web.config)
- easyui学习笔记2:页面布局,layout插件
- IOS UILabel 详解