This commit is contained in:
parent
f57321d95a
commit
587076ab11
@ -27,6 +27,10 @@
|
||||
- [KMP](./kmp.md)
|
||||
- [重复的子字符串](./repeated_substring_pattern.md)
|
||||
|
||||
# 栈与队列
|
||||
|
||||
- [用栈实现队列 && 用队列实现栈](./impl_stack_queue.md)
|
||||
|
||||
# 经典代码
|
||||
|
||||
- [合并两个有序链表](./merge_two_sorted_linked_lists.md)
|
||||
|
56
notes/src/impl_stack_queue.md
Normal file
56
notes/src/impl_stack_queue.md
Normal 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
|
||||
|
||||
```
|
Loading…
Reference in New Issue
Block a user