用两个栈实现队列 C++实现
2014-02-26 13:59
316 查看
//============================================================================ // Name : QueueRealizedByStack.cpp // Author : Lee // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <stack> using namespace std; template<typename T> class CQueue { public: CQueue() {} ~CQueue() {} void appendTail(const T& node); // append a element to tail void deleteHead(); // remove a element from head size_t size(); T front(); private: stack<T> m_stack1; stack<T> m_stack2; }; template<typename T> void CQueue<T>::appendTail(const T &node){ m_stack1.push(node); } template<typename T> void CQueue<T>::deleteHead(){ if(m_stack2.size()>0){ m_stack2.pop(); }else{ if(0==m_stack1.size()){ return; }else{ while(m_stack1.size()!=0){ m_stack2.push(m_stack1.top()); m_stack1.pop(); } m_stack2.pop(); } } } template<typename T> size_t CQueue<T>::size(){ return m_stack1.size()+m_stack2.size(); } template<typename T> T CQueue<T>::front(){ if(m_stack2.size()>0){ return m_stack2.top(); }else{ if(0==m_stack1.size()){ T t; return t; }else{ while(m_stack1.size()!=0){ m_stack2.push(m_stack1.top()); m_stack1.pop(); } return m_stack2.top(); } } } int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! CQueue<int> cq; cq.appendTail(4); cq.appendTail(3); cout<<cq.front(); return 0; }
相关文章推荐
- 《剑指offer》:[7]两个队列实现栈的C++代码实现
- C/C++之用两个栈实现一个队列的功能
- 两个栈来实现一个队列的C++代码
- 【C++】两个队列实现一个栈
- c++ 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 《剑指Offer》附加题_用两个队列实现一个栈_C++版
- coding interview guide-两个栈组成队列 C++实现
- 【C++】两个栈实现一个队列
- 两个栈来实现一个队列的C++代码
- 两个栈来实现一个队列的C++代码(某公司社会早笔试题)
- c++实现两个堆栈模拟一个队列
- C++面试题:两个队列实现一个栈
- C++两个栈实现一个队列
- c++ 两个栈实现队列
- 两个栈实现队列、两个队列实现栈 C++
- 算法学习记录五(C++)--->两个栈实现队列
- 面试题7:用两个栈实现队列的c++代码实现
- C++ 用两个栈实现一个队列
- 用两个栈实现队列 【C++实现】