[LeetCode] Implement Stack using Queues
2015-06-11 11:12
609 查看
Implement Stack using Queues
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 may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
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 -- which means only
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
水题。用两个队列来模拟。
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 may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
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 -- which means only
push to back,
pop from front,
size, and
is emptyoperations are valid.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
水题。用两个队列来模拟。
class Stack { private: queue<int> que[2]; int cur = 0; public: // Push element x onto stack. void push(int x) { que[cur].push(x); } // Removes the element on top of the stack. void pop(void) { while (que[cur].size() > 1) { que[1 - cur].push(que[cur].front()); que[cur].pop(); } que[cur].pop(); cur = 1 - cur; } // Get the top element. int top(void) { while (que[cur].size() > 1) { que[1 - cur].push(que[cur].front()); que[cur].pop(); } int top = que[cur].front(); que[1 - cur].push(que[cur].front()); que[cur].pop(); cur = 1 - cur; return top; } // Return whether the stack is empty. bool empty(void) { return que[cur].empty(); } };
相关文章推荐
- 51nod 1126 求递推序列的第N项 && hdu - 1005 Number Sequence (求周期)
- UI元素状态伪类选择器
- 3 way quick sort
- POJ 1458:Common Subsequence
- POJ 1458:Common Subsequence
- 非常不错的点餐系统应用源码完整版
- leetcode--Unique Binary Search Trees II
- A quick message queue benchmark: ActiveMQ, RabbitMQ, HornetQ, QPID, Apollo
- java 并发编程 AbstractQueuedSynchronizer 加锁和解锁分析
- UITableView的简单介绍和功能
- Null value was assigned to a property of primitive type setter of"原因及解决方
- powerbuilder开发的程序,查询功能中,listview中的属性列重复出现
- 为jenkins的每个build设置description
- Android含文档server结束(client UI接口异步请求的一部分)三
- 【EasyUI学习-2】Easyui Tree的异步加载
- 报错:ImportError: No module named 'requests'
- MUI实战开发第四集--如何增加自定义icon图标
- 关于使用unigui、webxone、mysql的几个问题
- java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
- UIPanGestureRecognizer手势影响UISlider拖动的问题及解决办法