利用两个栈实现一个队列(C++版)
2015-11-25 23:45
971 查看
题目:
利用两个栈实现一个队列的功能,完成pop() push() peek() empty()等功能。
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
主要思想:一个栈作为压入栈(只执行push操作),另一个栈作为弹出栈(只执行pop操作)。
push —— 执行压入操作时,将数据压入 压入栈。
pop —— 执行弹出操作时,必须将压入栈所有的数据压入弹出栈,然后取出弹出栈顶元素。
peek —— 只获取弹出栈栈顶元素 不弹出。
empty —— 只有两个栈都为空才返回true
实现函数代码如下:
利用两个栈实现一个队列的功能,完成pop() push() peek() empty()等功能。
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
主要思想:一个栈作为压入栈(只执行push操作),另一个栈作为弹出栈(只执行pop操作)。
push —— 执行压入操作时,将数据压入 压入栈。
pop —— 执行弹出操作时,必须将压入栈所有的数据压入弹出栈,然后取出弹出栈顶元素。
peek —— 只获取弹出栈栈顶元素 不弹出。
empty —— 只有两个栈都为空才返回true
实现函数代码如下:
class TwoStackQueue { public: // Push element x to the back of queue. void push(int x) { stackPush.push(x); } // Removes the element from in front of queue. void pop(void) { if(stackPop.empty() && !stackPush.empty()) { while(!stackPush.empty()) { stackPop.push(stackPush.top()); stackPush.pop(); } } stackPop.pop(); } // Get the front element. int peek(void) { if(stackPop.empty() && !stackPush.empty()) { while(!stackPush.empty()) { stackPop.push(stackPush.top()); stackPush.pop(); } } return stackPop.top(); } // Return whether the queue is empty. bool empty(void) { if(stackPush.empty() && stackPop.empty() ) { return true; } return false; } public: stack<int> stackPush; stack<int> stackPop; };
相关文章推荐
- C/C++ 笔试、面试题目大汇总2
- C/C++ 笔试、面试题目大汇总
- 2015-11-23
- 闲来无事,学学C语言
- 忽略大小写,比较字符串大小。
- 单片机:按键(使用中断)控制数码管的数字加减(c语言实现)
- C++编程的第一个程序
- C语言基础
- 第一讲 visual c++6.0概述
- c++文件的加密与解密
- 对C++中避免异常发生中的资源泄漏的认识
- 作了一个歌德巴赫猜想的程序分享下
- C++编程中的四个调试小技巧
- 简单的5*5,五子棋小游戏
- 环形队列的c++实现
- 头文件和源文件的区别
- C语言开发总结(七)
- c++ primer第五版(中文)习题答案 第三章第六节-多维数组
- C语言常见问题分析(1)
- 《C++ primer》英文第五版阅读笔记(二十)——类型转换