LeetCode *** 232. Implement Queue using Stacks
2016-04-08 10:45
399 查看
题目:
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).
分析:
用两个栈来维护即可。
代码:
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 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 { stack<int> stkfront; stack<int> stkback; public: // Push element x to the back of queue. void push(int x) { stkfront.push(x); } // Removes the element from in front of queue. void pop(void) { if(!stkfront.empty()){ while(!stkfront.empty()){ stkback.push(stkfront.top()); stkfront.pop(); } stkback.pop(); while(!stkback.empty()){ stkfront.push(stkback.top()); stkback.pop(); } } else exit(1); } // Get the front element. int peek(void) { if(!stkfront.empty()){ while(!stkfront.empty()){ stkback.push(stkfront.top()); stkfront.pop(); } int res=stkback.top(); while(!stkback.empty()){ stkfront.push(stkback.top()); stkback.pop(); } return res; } else return NULL; } // Return whether the queue is empty. bool empty(void) { return stkfront.empty(); } };
相关文章推荐
- requirejs和r.js的心得
- 重写的easyui-validatebox 验证规则
- UI 常用(UIButton)
- easyui-validatebox form表单提交时校验 ajax提交时校验
- Android中的requestWindowFeature()函数
- 去掉UItableview headerview黏性
- 如何现实隐藏UIBarButtonItem? show/hide a UIBarButtonItem
- Building VirtualBox OSE 5.0.0 on Windows 7 (x86)
- Strtus2——request、response等内置对象的获取方式
- 解决AndroidStduio出现merger failed with multiple errors, see logs
- UITableView 相关属性的设置
- zookeeper、zkui、kafka部署技术
- UICollectionView-设置内容的滚动方向
- UICollectionView-设置弹簧效果是否显示滚动条等向
- UICollectionView的初始化
- UICollectionView实例1
- com.mysql.jdbc.PacketTooBigException: Packet for query is too large (11707239 > 1048576). You can c
- 如果直接通过获得所有的UIBarButtonItem更改起返回按钮的图片-出现的问题
- iOS中UITableView的cell点击事件不触发didSelectRowAtIndexPath
- 卡片式UI的总结 android