LeetCode 225. Implement Stack using Queues
2016-07-24 17:25
465 查看
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only
and
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only
push to back,
peek/pop from front,
size,
and
is emptyoperations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
class Stack { public: queue<int> q; // Push element x onto stack. void push(int x) { queue<int> tmp; while(!q.empty()){ tmp.push(q.front()); q.pop(); } q.push(x); while(!tmp.empty()){ q.push(tmp.front()); tmp.pop(); } } // Removes the element on top of the stack. void pop() { q.pop(); } // Get the top element. int top() { return q.front(); } // Return whether the stack is empty. bool empty() { return q.empty(); } };
相关文章推荐
- [php]include()和require()区别【学习笔记】
- ueditor1_4_3_3编辑器修改文章
- POJ 3368 Frequent valuess
- UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 26269: illegal multibyte sequence
- HDU5301 Buildings [图形]
- Dubbo的广播模式下Can't assign requested address问题解决
- Java对象的强、软、弱和虚引用原理+结合ReferenceQueue对象构造Java对象的高速缓存器
- Bringing up interface eth0: Error: No suitable device found: no device found for connection ' Syste
- HDU 1509 Windows Message Queue (优先队列)
- HDU 5749 Colmerauer(单调栈+推公式)
- HDU 5749 Colmerauer 单调队列+暴力贡献
- JAVASE总结--05(continue、break)
- Arduino接收红外信号
- POJ 1019 Number Sequence
- codeforce 24D Broken robot—概率DP—conquersea博客
- 对数据集“dsArea”执行查询失败。 (rsErrorExecutingCommand),Query execution failed for dataset 'dsArea'. (rsErrorExecutingCommand),Manually process the TFS data warehouse and analysis services cube
- 递归搜索 ( 水题 )——A Rational Sequence ( UVA 7363 )
- poj 2524 Ubiquitous Religions [并查集]
- jeasyui扩展:combogrid实现本地数据过滤
- Vue.js - 学习笔记 (一)