理论基础
STL 队列和栈不被归类为容器,而被归类为container adapter( 容器适配器)
如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构,也可以指定vector或list作为底层实现:
std::queue<int, std::list<int>> third; // 定义以list为底层容器的队列
std::stack<int, std::vector<int> > third; // 使用vector为底层容器的栈
232.用栈实现队列
本题需要定义两个栈来模拟队列,第一个栈stackin用于模拟入队列时的操作,第二个栈stackout用于辅助模拟出队列时候的操作,因为队列是先入先出,栈是先入后出,所以在弹出元素时操作就复杂一些,stackout如果为空,就把stackin数据全部弹出并导入进stackin(注意是全部导入),再从stackout弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。
另外,peek函数用于返回队列开头元素,和pop的区别在于不会弹出该元素,因此可以复用pop函数,再将该元素放回原处即可
问题:void std::stack<int>::pop(),栈的pop操作返回值为空,无法知道pop的元素具体值?
解决:使用top()函数知道栈顶元素值
class MyQueue {
public:
stack<int> stin;
stack<int> stout;
MyQueue() {
}
void push(int x) {
stin.push(x);
}
int pop() {
//输出栈为空 将输入栈全体移入
if (stout.empty() == true) {
while (stin.empty() != true) {
stout.push(stin.top());
stin.pop();
}
}
int x = stout.top();
stout.pop();
return x;
}
int peek() {
//复用pop函数
int x=this->pop();
stout.push(x);
return x;
}
//两个栈都为空说明是空的
bool empty() {
if (stin.empty() == true && stout.empty() == true)return true;
else return false;
}
};
225. 用队列实现栈
本题只需要用一个队列即可实现栈的功能,其中push操作相同,不影响,pop操作需要将队列中除了队尾最后一个元素(相当于需要pop的栈顶元素)不变,其余元素依次从头排到队尾,实现换位操作,再进行队列的pop,就可以移除栈顶元素
此外,栈顶元素相当于队尾元素,因此top操作相当于是找queue的队尾元素
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size--;
//除了最后一个都进行换位
while (size--) {
//队头元素
int t = que.front();
que.pop();
que.push(t);
}
int result = que.front();
//此时pop的相当于栈顶元素
que.pop();
return result;
}
int top() {
return que.back();
}
bool empty() {
return que.empty();
}
};