则把第一个栈中的数据全部压入第二个栈(第一个栈此时为空)。
实际写代码时注意栈为空的情况。
代码:
#include <iostream> #include <stack> class Queue { public: Queue() {} ~Queue() {} void push(int vData) { m_First.push(vData); } void pop() { if (m_Second.empty()) { if (m_First.empty()) { std::cout << "the queue is empty" << std::endl; return ; } move(m_First, m_Second); m_Second.pop(); } } int top() { if (m_Second.empty()) { if (m_First.empty()) { std::cout << "the queue is empty" << std::endl; return ; } move(m_First, m_Second); } return m_Second.top(); } int back() { if (m_First.empty()) { if (m_Second.empty()) { std::cout << "the queue is empty" << std::endl; return ; } move(m_Second, m_First); } return m_First.top(); } private: void move(std::stack<int>& vL, std::stack<int>& vR) { while (!vL.empty()) { vR.push(vL.top()); vL.pop(); } } private: std::stack<int> m_First; std::stack<int> m_Second; };
原文地址:http://blog.csdn.net/xiaoliangsky/article/details/38859647