File tree Expand file tree Collapse file tree 1 file changed +97
-1
lines changed
Expand file tree Collapse file tree 1 file changed +97
-1
lines changed Original file line number Diff line number Diff line change @@ -203,8 +203,104 @@ public boolean empty() {
203203![ labuladong] ( ../pictures/labuladong.jpg )
204204
205205
206+ [ Xingsheng Qi] ( https://github.com/ziggy7 ) 提供 用栈实现队列 C++解法代码:
207+
208+ ``` CPP
209+ class MyQueue {
210+ private:
211+ stack<int > s1;
212+ stack<int > s2;
213+
214+ public:
215+ MyQueue() {
216+ }
217+
218+ /** 添加元素到队尾 * /
219+ void push(int x) {
220+ s1.push(x);
221+ }
222+
223+ /** 删除队头的元素并返回 * /
224+ int pop() {
225+ // 先调用 peek 保证 s2 非空
226+ peek();
227+ //保存 s2 的栈顶元素用于返回
228+ int tmp = s2.top();
229+ s2.pop();
230+ return tmp;
231+ }
232+
233+ /** 返回队头元素 * /
234+ int peek() {
235+ if (s2.empty())
236+ // 把 s1 元素压入 s2
237+ while (!s1.empty()){
238+ s2.push(s1.top());
239+ s1.pop();
240+ }
241+ return s2.top();
242+ }
243+
244+ /** 判断队列是否为空 * /
245+ bool empty() {
246+ return s1.empty()&& s2.empty();
247+ }
248+ };
249+ ```
250+
251+ [Xingsheng Qi](https://github.com/ziggy7) 提供 用队列实现栈 C++解法代码:
252+
253+ ```CPP
254+ class MyStack {
255+ private:
256+ queue<int>q;
257+ int top_elem = 0;
258+
259+ public:
260+ MyStack() {
261+
262+ }
263+
264+ /** 添加元素到栈顶 */
265+ void push(int x) {
266+ // x 是队列的队尾,是栈的栈顶
267+ q.push(x);
268+ top_elem = x;
269+ }
270+
271+ /** 删除栈顶的元素并返回 */
272+ int pop() {
273+ int size = q.size();
274+ // 留下队尾 2 个元素
275+ while (size > 2) {
276+ q.push(q.front());
277+ q.pop();
278+ size--;
279+ }
280+ // 记录新的队尾元素
281+ top_elem = q.front();
282+ q.push(q.front());
283+ q.pop();
284+ // 删除之前的队尾元素
285+ int tmp = q.front();
286+ q.pop();
287+ return tmp;
288+ }
289+
290+ /** 返回栈顶元素 */
291+ int top() {
292+ return top_elem;
293+ }
294+
295+ /** 判断栈是否为空 */
296+ bool empty() {
297+ return q.empty();
298+ }
299+ };
300+ ```
301+
206302[上一篇:递归反转链表的一部分](../数据结构系列/递归反转链表的一部分.md)
207303
208304[下一篇:算法学习之路](../算法思维系列/算法学习之路.md)
209305
210- [ 目录] ( ../README.md#目录 )
306+ [目录](../README.md#目录)
You can’t perform that action at this time.
0 commit comments