leetcode 232: Implement Queue using Stacks
2015-08-30 15:10
393 查看
Use two stacks. Every time I need to pop, I push all numbers in st1 into st2 except the last one, then I pop that one. After that, I push back all numbers into st1. Don't forget to update the front variable.
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
if(st1.empty())
front=x;
st1.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
while(st1.size()!=1)
{
st2.push(st1.top());
st1.pop();
}
st1.pop();
if(!st2.empty())
front=st2.top();
while(!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
}
// Get the front element.
int peek(void) {
return front;
}
// Return whether the queue is empty.
bool empty(void) {
return st1.empty();
}
private:
stack<int> st1;
stack<int> st2;
int front;
};
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
if(st1.empty())
front=x;
st1.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
while(st1.size()!=1)
{
st2.push(st1.top());
st1.pop();
}
st1.pop();
if(!st2.empty())
front=st2.top();
while(!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
}
// Get the front element.
int peek(void) {
return front;
}
// Return whether the queue is empty.
bool empty(void) {
return st1.empty();
}
private:
stack<int> st1;
stack<int> st2;
int front;
};
相关文章推荐
- HDU 3397 Sequence operation(线段树区间合并)
- 野人学Android基础篇之初探UI控件第六课--ListView和他的adapter们(二)
- The Java EE 6 Tutorial Filtering Requests and Responses
- 如何找到最合适处理事件的UIView
- UUID iOS设备唯一标示符
- STL源码剖析 [容器](六)[stl_queue.h]
- [算法] Quick Sort
- iOS开发笔记1-UINavigationController
- UVa 1608:Non-boring swquences(分治)
- CEGUI编译
- EasyUI常用控件禁用方法
- UIimage View
- UIButton状态:添加图片:
- 剖析安卓build系统的设计思想以及案例模拟
- iphone开发之表格组件UITableView的使用(二)如何分组展示数据并添加组头和组尾描述
- easyui使用mergeCells合并单元格后第一行行高过大
- iOS开发 - UIAlertController 弹框提醒
- 考评系统学到的UI设计理念
- UIWindow和UIView
- UI设计规范