57 lines
1.3 KiB
Markdown
57 lines
1.3 KiB
Markdown
|
# 用栈实现队列 && 用队列实现栈
|
||
|
|
||
|
## 用栈实现队列
|
||
|
|
||
|
[Leetcode](https://leetcode.com/problems/implement-queue-using-stacks/)
|
||
|
|
||
|
「输入栈」会把输入顺序颠倒;如果把「输入栈」的元素逐个弹出放到「输出栈」,再从「输出栈」弹出元素的时候,则可以负负得正,实现了先进先出。
|
||
|
|
||
|
```cpp
|
||
|
#include <stack>
|
||
|
|
||
|
class MyQueue {
|
||
|
public:
|
||
|
std::stack<int> *inStack, *outStack;
|
||
|
|
||
|
MyQueue() {
|
||
|
inStack = new std::stack<int>;
|
||
|
outStack = new std::stack<int>;
|
||
|
}
|
||
|
|
||
|
void transfer(void) {
|
||
|
if (outStack->empty()) {
|
||
|
while (!inStack->empty()) {
|
||
|
outStack->push(inStack->top());
|
||
|
inStack->pop();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void push(int x) { inStack->push(x); }
|
||
|
|
||
|
int pop() {
|
||
|
transfer();
|
||
|
int val = outStack->top();
|
||
|
outStack->pop();
|
||
|
return val;
|
||
|
}
|
||
|
|
||
|
int peek() {
|
||
|
transfer();
|
||
|
return outStack->top();
|
||
|
}
|
||
|
|
||
|
bool empty() { return inStack->empty() && outStack->empty(); }
|
||
|
};
|
||
|
```
|
||
|
|
||
|
## 用队列实现栈
|
||
|
|
||
|
[Leetcode](https://leetcode.com/problems/implement-stack-using-queues/)
|
||
|
|
||
|
一个队列为主队列,一个为辅助队列,当入栈操作时,我们先将主队列内容导入辅助队列,然后将入栈元素放入主队列队头位置,再将辅助队列内容,依次添加进主队列即可。
|
||
|
|
||
|
```cpp
|
||
|
|
||
|
```
|