栈与队列理论
栈是先进后出,队列是先进先出。
栈和队列是STL(C++标准库)里面的两个数据结构。
栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 不像是set 或者map 提供迭代器iterator来遍历所有元素。
栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
所以STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器)。
栈的底层实现可以是vector,deque,list 都是可以的, 主要就是数组和链表的底层实现。
以下是指定vector和list为底层实现的例子:
std::stack<int, std::vector<int>> third;
std::queue<int, std::list<int>> third;
栈的操作
方法 | 作用 |
---|---|
push(x) | 从栈顶加入一个元素 |
pop() | 从栈顶弹出一个元素 |
top() | 返回栈顶元素 |
size() | 返回栈元素个数 |
empty() | 返回是否为空的布尔值 |
队列的操作
方法 | 作用 |
---|---|
push(x) | 从队列尾加入一个元素 |
pop() | 从队列头弹出一个元素 |
front () | 返回队列头元素 |
back () | 返回队列尾元素 |
size() | 返回队列元素个数 |
empty() | 返回是否为空的布尔值 |
232.用栈实现队列
题目链接:232. 用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
思路:
想用栈实现队列的先入先出,则需要用到两个栈,一个用来入栈一个用来出栈,而出栈的顺序就是题目所规定的顺序。入栈的元素一定要全放到出栈里,否则顺序会乱掉。
可以写出如下代码:
class MyQueue {
public:
stack<int> stackIn;
stack<int> stackOut;
MyQueue() {
}
void push(int x) {
stackIn.push(x);
}
int pop() {
if (stackOut.empty())
{
while (!stackIn.empty())
{
stackOut.push(stackIn.top());
stackIn.pop();
}
}
int result = stackOut.top();
stackOut.pop();
return result;
}
int peek() {
if (stackOut.empty())
{
while (!stackIn.empty())
{
stackOut.push(stackIn.top());
stackIn.pop();
}
}
int result = stackOut.top();
return result;
}
bool empty() {
return stackIn.empty() && stackOut.empty();
}
};
225. 用队列实现栈
题目链接:225. 用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
思路:
这道题可以用两个队列模拟栈,也可以用一个队列模拟栈。个人觉得两个队列模拟栈的思路有些复杂,所以这里只讨论使用一个队列。
一个队列在模拟栈弹出元素的时候只要将队列前部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
代码实现:
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int result = que.back();
int length = que.size();
for (int i = 0; i<length-1;i++)
{
que.push(que.front());
que.pop();
}
que.pop();
return result;
}
int top() {
return que.back();
}
bool empty() {
return que.empty();
}
};