Implement Stack using Queues
来源:互联网 发布:java.util.*是什么包 编辑:程序博客网 时间:2024/06/09 18:56
mplement 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 push to back, peek/pop from front, size, and is empty operations 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).
方法:队列实现栈,注意将数字压入到队列中时需要循环出队进队模拟栈,效率不高。
class MyStack {private: queue<int> q;public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { q.push(x); for(int i = 0 ; i < q.size() - 1; ++i){ q.push(q.front()); q.pop(); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int res = q.front(); q.pop(); return res; } /** Get the top element. */ int top() { return q.front(); } /** Returns whether the stack is empty. */ bool empty() { return q.empty(); }};/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * bool param_4 = obj.empty(); */
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Implement Stack using Queues
- Spark SQL和DataFrames支持的数据格式
- LeetCode链表操作常见面试题汇总
- Unsupported major.minor version (jdk版本错误)解决方案
- DS1302
- jupyter安装过程错误记录
- Implement Stack using Queues
- [Freemark]freemark常用语法
- 八皇后问题
- 最长上升子序列
- 盒子模型
- 子查询
- Ford-Fulkerson算法模板(最大流)
- LCD常用接口
- 块级元素与内联元素的区别