基础理论
-
栈和队列是C++ STL中的结构,具体实现得看具体STL版本(普遍三个)
- HP STL,第一个实现的,开源,其他基本都是参考这个实现的
- P.J.Plauger STL ,Visual C++采用,未开源
- SGI STL,被Linux的GCC采用,开源,源码可读性很高
-
不允许有遍历行为,所以并不是迭代器
-
可以指定队列和栈的底层实现
std::stack<int, std::vector<int> > third;std::queue <int, std::list<int>> third;
栈
- 先进后出,提供push、pop、top等接口,不提供走访功能,也不提供迭代器功能(不像map和set)
- 以底层容器完成其所有的工作,对外提供统一接口,底层容器是可插拔的(或者说可以控制使用哪种容器来实现栈的功能)
- STL一般不被归为容器,而是container adapter(容器适配器)
- 栈的底层可以是vector、deque、list,主要是数组和链表的底层实现
- 常用的SGI STL,没有指定的话默认即以deque(双向队列,封住一端即可)为底层实现栈
队列
- 先进先出
- SGI STL中默认也是以deque为底层实现队列
232. 用栈实现队列
心得
- 想到两个栈实现队列,empty判断失误,pop和top函数需要熟悉,pop返回void,需要值必须要先top,如果移除需要再pop
题解
- 双栈实现,注意peak可以取巧,empty返回含义有点绕,需要考虑下
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
in.push(x);
}
int pop() {
if (out.empty()) {
while (!in.empty()) {
out.push(in.top());
in.pop();
}
}
int result = out.top();
out.pop();
return result;
}
int peek() {
int result = this->pop();
out.push(result);
return result;
}
bool empty() {
return in.empty() && out.empty();
}
private:
stack<int> in;
stack<int> out;
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
225. 用队列实现栈
心得
- 开始想到双队列,一个保存除末尾的其他位置,类似一个temp,每次留最后一个出来进行访问
题解
- 单队列即可
- 注意队列的size front 区别top等操作,需要熟悉STL基本操作
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
int result;
size--;
while (size--) {
que.push(que.front());
que.pop();
}
result = que.front();
que.pop();
return result;
}
int top() {
return que.back();
}
bool empty() {
return que.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();
*/