利用两个队列实现一个栈(C++版)
2015-11-26 00:50
786 查看
题目:
利用两个队列实现一个栈的功能,完成pop() push() top() empty()等功能。
push(x) -- Push element x into stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty
思路:
两个队列q1, q2。不管是插入还是弹出,保证总有一个队列为空。那么:
队列入栈:将元素插入空队列,同时将非空队列的元素依次插入到空队列。此时之前的非空队列变为空队列,空队列变为非空队列。
队列出栈:将非空队列的队首弹出即可。
举例说明:
执行下述操作:先将1 2 3入栈,接着3出栈,然后4入栈。两个队列元素的变化情况如下:
1. 初始:q1 q2为空 将1压入q1。此时q1非空 q2为空。
2. 元素2入栈 q2为空 压入。之前q1非空,将1弹出压入q2。此时q1为空 q2为2 1。
3.
元素3入栈 q1为空 压入。之前q2非空,将2 1依次弹出压入q1。此时q2为空 q1为3 2 1。
4.
元素3出栈 q1非空 3出栈。q1为2
1 q2为空。
5.
元素4入栈 q2为空 压入。之前q1非空,将2 1依次弹出压入q2。此时q1为空 q2为4 2 1。
实现函数代码如下:
利用两个队列实现一个栈的功能,完成pop() push() top() empty()等功能。
push(x) -- Push element x into stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty
思路:
两个队列q1, q2。不管是插入还是弹出,保证总有一个队列为空。那么:
队列入栈:将元素插入空队列,同时将非空队列的元素依次插入到空队列。此时之前的非空队列变为空队列,空队列变为非空队列。
队列出栈:将非空队列的队首弹出即可。
举例说明:
执行下述操作:先将1 2 3入栈,接着3出栈,然后4入栈。两个队列元素的变化情况如下:
1. 初始:q1 q2为空 将1压入q1。此时q1非空 q2为空。
2. 元素2入栈 q2为空 压入。之前q1非空,将1弹出压入q2。此时q1为空 q2为2 1。
3.
元素3入栈 q1为空 压入。之前q2非空,将2 1依次弹出压入q1。此时q2为空 q1为3 2 1。
4.
元素3出栈 q1非空 3出栈。q1为2
1 q2为空。
5.
元素4入栈 q2为空 压入。之前q1非空,将2 1依次弹出压入q2。此时q1为空 q2为4 2 1。
实现函数代码如下:
class QueueStack { public: // 保证每个时刻都有一个队列为空队列 // Push element x onto stack. void push(int x) { if(q1.empty()) { q1.push(x); while(!q2.empty()) { q1.push(q2.front()); q2.pop(); } } else { q2.push(x); while(!q1.empty()) { q2.push(q1.front()); q1.pop(); } } } // Removes the element on top of the stack. void pop() { if(q1.empty()) { q2.pop(); } else { q1.pop(); } } // Get the top element. int top() { if(q1.empty()) { return q2.front(); } else { return q1.front(); } } // Return whether the stack is empty. bool empty() { return (q1.empty() && q2.empty()); } queue<int> q1; queue<int> q2; };
相关文章推荐
- 个人笔记-从零开始iOS开发_C语言基础1
- C语言访问网页
- 【C语言】第二章 类型、运算符和表达式
- mysql connector c++的一些坑
- leetcode笔记:Combination Sum
- 利用两个栈实现一个队列(C++版)
- C/C++ 笔试、面试题目大汇总2
- C/C++ 笔试、面试题目大汇总
- 2015-11-23
- 闲来无事,学学C语言
- 忽略大小写,比较字符串大小。
- 单片机:按键(使用中断)控制数码管的数字加减(c语言实现)
- C++编程的第一个程序
- C语言基础
- 第一讲 visual c++6.0概述
- c++文件的加密与解密
- 对C++中避免异常发生中的资源泄漏的认识
- 作了一个歌德巴赫猜想的程序分享下
- C++编程中的四个调试小技巧
- 简单的5*5,五子棋小游戏