From 587076ab113af839d828c940759a09be82598c3b Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 6 Dec 2022 17:24:52 +0800 Subject: [PATCH] Add impl stack queue --- notes/src/SUMMARY.md | 4 +++ notes/src/impl_stack_queue.md | 56 +++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 notes/src/impl_stack_queue.md diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md index 157bb92..f86fc7c 100644 --- a/notes/src/SUMMARY.md +++ b/notes/src/SUMMARY.md @@ -27,6 +27,10 @@ - [KMP](./kmp.md) - [重复的子字符串](./repeated_substring_pattern.md) +# 栈与队列 + +- [用栈实现队列 && 用队列实现栈](./impl_stack_queue.md) + # 经典代码 - [合并两个有序链表](./merge_two_sorted_linked_lists.md) diff --git a/notes/src/impl_stack_queue.md b/notes/src/impl_stack_queue.md new file mode 100644 index 0000000..b36465c --- /dev/null +++ b/notes/src/impl_stack_queue.md @@ -0,0 +1,56 @@ +# 用栈实现队列 && 用队列实现栈 + +## 用栈实现队列 + +[Leetcode](https://leetcode.com/problems/implement-queue-using-stacks/) + +「输入栈」会把输入顺序颠倒;如果把「输入栈」的元素逐个弹出放到「输出栈」,再从「输出栈」弹出元素的时候,则可以负负得正,实现了先进先出。 + +```cpp +#include + +class MyQueue { + public: + std::stack *inStack, *outStack; + + MyQueue() { + inStack = new std::stack; + outStack = new std::stack; + } + + 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 + +```