栈和队列的基础知识
- C++中stack 是容器么?
- 我们使用的stack是属于哪个版本的STL?
- 我们使用的STL中stack是如何实现的?
- stack 提供迭代器来遍历stack空间么?
栈
- STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器, 底层容器是可插拔)
- 总共有三个版本:
- HP STL是C++ STL的第一个实现版本,而且开放源代码;
- P.J.Plauger STL 参照HP STL实现出来的,被Visual C++编译器所采用,不是开源的
- SGI STL参照HP STL实现,被Linux的C++编译器GCC所采用,SGI STL是开源软件 (常用)
- 栈的内部结构,栈的底层实现可以是vector,deque,list 都是可以的, 主要就是数组和链表的底层实现.
- SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构
std::stack<int, std::vector<int> > third; // 使用vector为底层容器的栈
- 栈不提供走访功能,也不提供迭代器(iterator),所有元素必须符合先进后出规则
- 不像是set 或者map 提供迭代器iterator来遍历所有元素
队列
栈常见的操作函数
- push, pop
- empty, size
- top
队列常见的操作函数
- front, back
- push, pop
- empty, size
232. 用栈实现队列
模拟实现的过程
- 队列为先进先出
- 栈为先进后出
- 需要使用两个栈来调换顺序
知识点:
- 如何new分配空间(一般不怎么使用)
//自行实现
class MyQueue {
public:
stack<int> stin;
stack<int> stout;
MyQueue() {
}
void swap() {
if (stout.empty()) {
while (!stin.empty()) {
int tem = stin.top();
stin.pop();
stout.push(tem);
}
}
}
void push(int x) {
stin.push(x);
}
int pop() {
swap();
int tem = stout.top();
stout.pop();
return tem;
}
int peek() {
swap();
return stout.top();
}
bool empty() {
swap();
return stout.empty();
}
};
/**
* 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. 用队列实现栈
思路: 双队列实现,
class MyStack {
public:
queue<int> queue1;
queue<int> queue2;
MyStack() {}
void push(int x) {
if (queue1.empty()) {
queue2.push(x);
} else {
queue1.push(x);
}
}
int pop() {
int res;
if (queue1.empty()) {
res = queue2.back();
while (queue2.size() != 1) {
int tem = queue2.front();
queue2.pop();
queue1.push(tem);
}
queue2.pop();
} else {
res = queue1.back();
while (queue1.size() != 1) {
int tem = queue1.front();
queue1.pop();
queue2.push(tem);
}
queue1.pop();
}
return res;
}
int top() {
if (queue1.empty()) {
return queue2.back();
} else {
return queue1.back();
}
}
bool empty() { return queue1.empty() && queue2.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();
*/