用两个栈实现一个队列,用两个队列实现一个栈,C++ STL版
来源:互联网 发布:什么是栅格数据 编辑:程序博客网 时间:2024/06/03 15:35
不必解释了吧,这里代码应该就能说明问题了
#include <iostream>#include <stack>#include <queue>using namespace std;//Queuetemplate<typename T>class Queue{public: void pop(void); void push(const T& t); const T& front(void); bool empty(void) const;private: void left_to_rigth(void); stack<T> left_,right_;};template<typename T>void Queue<T>::left_to_rigth(void){ while(!left_.empty()) { right_.push(left_.top()); left_.pop(); }}template<typename T>bool Queue<T>::empty(void) const{ return (left_.empty() && right_.empty());}template<typename T>void Queue<T>::push(const T& t){ left_.push(t);}template<typename T>void Queue<T>::pop(void){ if (!right_.empty()) { right_.pop(); } else if (!left_.empty()) { left_to_rigth(); } else { throw "Queue is empty now ,can not pop!"; }}template<typename T>const T& Queue<T>::front(void){ if (!right_.empty()) { return right_.top(); } else if (!left_.empty()) { left_to_rigth(); return right_.top(); } else { throw "empty queu can not return front"; }}//Stacktemplate<typename T>class Stack{public: void pop(void); void push(const T& t); const T& top(void); bool empty(void);private: void left_to_rigth(void); queue<T> left_,right_;};template<typename T>void Stack<T>::left_to_rigth(void){ if (!left_.empty()) { int move = left_.size() -1; while (move > 0) { right_.push(left_.front()); left_.pop(); --move; } }}template<typename T>bool Stack<T>::empty(){ return (left_.empty() && right_.empty());}template<typename T>void Stack<T>::push(const T& t){ left_.push(t);}template<typename T>void Stack<T>::pop(void){ left_to_rigth(); left_.swap(right_); right_.pop();}template<typename T>const T& Stack<T>::top(void){ if (!left_.empty()) { left_to_rigth(); left_.swap(right_); const T& temp = right_.front(); left_.push(right_.front()); right_.pop(); return temp; } else { throw "empty stack can not return top!"; }}int main () { Queue<int> queue_int; cout<<"test queue : "; for(int i=0;i<10;++i) { queue_int.push(i); } while(!queue_int.empty()) { cout<<queue_int.front()<<" "; queue_int.pop(); } cout<<endl; Stack<int> stack_int; cout<<"test stack : "; for(int i=0;i<10;++i) { stack_int.push(i); } while(!stack_int.empty()) { cout<<stack_int.top()<<" "; stack_int.pop(); } cout<<endl; return 0;}
0 0
- 用两个栈实现一个队列,用两个队列实现一个栈,C++ STL版
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 两个栈实现一个队列(C/C++)
- 用两个栈实现一个队列
- 用两个栈实现一个队列
- 用两个栈实现一个队列
- 用两个队列实现一个栈
- 用两个栈实现一个队列功能
- 用两个栈实现一个队列
- 用两个队列实现一个栈
- 用两个栈实现一个队列
- 用两个队列实现一个栈
- 用两个栈来实现一个队列
- 用两个栈实现一个队列功能
- 用两个队列实现一个栈
- 用两个队列实现一个栈
- 用两个栈实现一个队列
- java 数字签名快捷方法
- 常见进程间的通信方式
- Zookeeper的单机安装和调试
- mybatis加Spring项目: 解决There is no getter for property named '***' in 'class java.lang.String'问题
- linux iic driver1
- 用两个栈实现一个队列,用两个队列实现一个栈,C++ STL版
- git config第三篇——git的常用配置
- UVA 10115
- CC2540的HAL层UART学习笔记
- 胳膊好累,胳膊好酸,明天还怎么工作
- POJ_3233_Matrix Power_矩阵快速幂/二分法
- Python re正则表达式
- 立即发了多少减肥了开始的减肥
- C_C语言的enum、struct、union的使用详解