From ed93c697c2fdc7de6b1a2d12138319190d75a091 Mon Sep 17 00:00:00 2001 From: ziggy7 <52338997+ziggy7@users.noreply.github.com> Date: Tue, 23 Jun 2020 17:03:10 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E7=94=A8=E6=A0=88?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E9=98=9F=E5=88=97=20=E5=92=8C=20=E7=94=A8?= =?UTF-8?q?=E9=98=9F=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88=20c++=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 解法思路与原作者相同 --- ...36\347\216\260\351\230\237\345\210\227.md" | 98 ++++++++++++++++++- 1 file changed, 97 insertions(+), 1 deletion(-) diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204\347\263\273\345\210\227/\351\230\237\345\210\227\345\256\236\347\216\260\346\240\210\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227.md" "b/\346\225\260\346\215\256\347\273\223\346\236\204\347\263\273\345\210\227/\351\230\237\345\210\227\345\256\236\347\216\260\346\240\210\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227.md" index ee63c22..e361f61 100644 --- "a/\346\225\260\346\215\256\347\273\223\346\236\204\347\263\273\345\210\227/\351\230\237\345\210\227\345\256\236\347\216\260\346\240\210\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227.md" +++ "b/\346\225\260\346\215\256\347\273\223\346\236\204\347\263\273\345\210\227/\351\230\237\345\210\227\345\256\236\347\216\260\346\240\210\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227.md" @@ -203,8 +203,104 @@ public boolean empty() { ![labuladong](../pictures/labuladong.jpg) +[Xingsheng Qi](https://github.com/ziggy7) 提供 用栈实现队列 C++解法代码: + +```CPP +class MyQueue { +private: + stack s1; + stack s2; + +public: + MyQueue() { + } + + /** 添加元素到队尾 */ + void push(int x) { + s1.push(x); + } + + /** 删除队头的元素并返回 */ + int pop() { + // 先调用 peek 保证 s2 非空 + peek(); + //保存 s2 的栈顶元素用于返回 + int tmp = s2.top(); + s2.pop(); + return tmp; + } + + /** 返回队头元素 */ + int peek() { + if (s2.empty()) + // 把 s1 元素压入 s2 + while (!s1.empty()){ + s2.push(s1.top()); + s1.pop(); + } + return s2.top(); + } + + /** 判断队列是否为空 */ + bool empty() { + return s1.empty()&& s2.empty(); + } +}; +``` + +[Xingsheng Qi](https://github.com/ziggy7) 提供 用队列实现栈 C++解法代码: + +```CPP +class MyStack { +private: + queueq; + int top_elem = 0; + +public: + MyStack() { + + } + + /** 添加元素到栈顶 */ + void push(int x) { + // x 是队列的队尾,是栈的栈顶 + q.push(x); + top_elem = x; + } + + /** 删除栈顶的元素并返回 */ + int pop() { + int size = q.size(); + // 留下队尾 2 个元素 + while (size > 2) { + q.push(q.front()); + q.pop(); + size--; + } + // 记录新的队尾元素 + top_elem = q.front(); + q.push(q.front()); + q.pop(); + // 删除之前的队尾元素 + int tmp = q.front(); + q.pop(); + return tmp; + } + + /** 返回栈顶元素 */ + int top() { + return top_elem; + } + + /** 判断栈是否为空 */ + bool empty() { + return q.empty(); + } +}; +``` + [上一篇:递归反转链表的一部分](../数据结构系列/递归反转链表的一部分.md) [下一篇:算法学习之路](../算法思维系列/算法学习之路.md) -[目录](../README.md#目录) \ No newline at end of file +[目录](../README.md#目录) -- GitLab