栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 不像是set 或者map 提供迭代器iterator来遍历所有元素。
我们常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。SGI STL中 队列底层实现缺省情况下一样使用deque实现的。
deque是一个双向队列,只要封住一段,只开通另一端就可以实现栈的逻辑了。
std::stack<int, std::vector<int> > third; // 使用vector为底层容器的栈
std::queue<int, std::list<int>> third; // 定义以list为底层容器的队列
所以STL中栈和队列往往不被归类为容器,而被归类为container adapter(容器适配器)。
正常初始化
stack<int> stack_in;
stack<int> stack_out;
232.用栈实现队列
#include <iostream>
class MyQueue {
public:
stack<int> stack_in;
stack<int> stack_out;
MyQueue() {
}
void push(int x) {
stack_in.push(x);
}
int pop() {
// 方法1
// if (stack_out.empty()){
// while (!stack_in.empty()){
// stack_out.push(stack_in.top());
// stack_in.pop();
// }
// }
// int res = stack_out.top();
// stack_out.pop();
// return res;
// 方法2, 调用peek
int res = peek();
stack_out.pop();
return res;
}
int peek() {
if (stack_out.empty()){
while (!stack_in.empty()){
int top_num = stack_in.top();
stack_in.pop();
stack_out.push(top_num);
}}
return stack_out.top();
// 方法2, 实现pop后调用pop
// int res = pop();
// stack_out.push(res); //push back
// return res;
}
bool empty() {
return (stack_in.empty()) && (stack_out.empty());
}
};
时间复杂度: push和empty为O(1), pop和peek为O(n)
空间复杂度: O(n)