Add impl stack queue
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Sainnhe Park 2022-12-06 17:24:52 +08:00
parent f57321d95a
commit 587076ab11
2 changed files with 60 additions and 0 deletions

View File

@ -27,6 +27,10 @@
- [KMP](./kmp.md)
- [重复的子字符串](./repeated_substring_pattern.md)
# 栈与队列
- [用栈实现队列 && 用队列实现栈](./impl_stack_queue.md)
# 经典代码
- [合并两个有序链表](./merge_two_sorted_linked_lists.md)

View File

@ -0,0 +1,56 @@
# 用栈实现队列 && 用队列实现栈
## 用栈实现队列
[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
```