重点
- 栈和队列是STL(C++标准库)里面的两个数据结构。
- 栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
- 所以STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器)。
- 我们常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。
- SGI STL中队列一样是以deque为缺省情况下的底部结构。
- 在工业级别代码开发中,最忌讳的就是 实现一个类似的函数,直接把代码粘过来改一改就完事了。
- 一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时在去弹出元素就是栈的顺序了。
刷题笔记
//232
class MyQueue {
public:
stack<int> stIn; //定义一个栈
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x); //栈的push()方法
}
int pop() {
if(stOut.empty()){ //判断栈是否为空
while(!stIn.empty()){
stOut.push(stIn.top());//栈的top()
stIn.pop();//栈的pop()
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
return result;
}
bool empty() {
return stIn.empty() && 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> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);//队列的push(),队尾加一个元素
}
int pop() {
while(que1.size() > 1){
int a = que1.front();//访问队列第一个元素
que1.pop(); //删除队列第一个元素,没有返回值
que2.push(a);
}
int result = que1.front();
que1.pop();
while(!que2.empty()){//队列判空,和栈一样
int b = que2.front();
que2.pop();
que1.push(b);
}
return result;
}
int top() {
int result = this->pop();
que1.push(result);
return result;
}
bool empty() {
if(que1.empty()) return true;
else return false;
}
};
/**
* 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();
*/