templateclass CQueue{public: CQueue(){} ~CQueue(){} void AppendTail(const TYPE& node); TYPE DeleteHead();private: stack m_stPushStack; stack m_stPopStack;};// 方法一:// 插入时 --> m_stPopStack不为空,将元素压入m_stPushStack;// 删除时 --> m_stPushStack不为空,将元素压入 m_stPopStack;// 方法二:// 插入时 --> 直接往 m_stPushStack 插入新元素// 删除时 --> 如果m_stPopStack为空,插入m_stPushStack中元素,否则直接弹出元素template TYPE CQueue ::DeleteHead(){#if 0 while (!m_stPushStack.empty()) { m_stPopStack.push(m_stPushStack.top()); m_stPushStack.pop(); }#else if (m_stPopStack.empty()) { while (!m_stPushStack.empty()) { m_stPopStack.push(m_stPushStack.top()); m_stPushStack.pop(); } }#endif TYPE tmp = m_stPopStack.top(); m_stPopStack.pop(); return tmp;}template void CQueue ::AppendTail(const TYPE& node){#if 0 while (!m_stPopStack.empty()) { m_stPushStack.push(m_stPopStack.top()); m_stPopStack.pop(); } m_stPushStack.push(node);#else m_stPushStack.push(node);#endif }void QueueWithTwoStackTestFunc(){ cout << "\n\n --------------- QueueWithTwoStackTestFunc Start -------------->" << endl; CQueue stQueue; stQueue.AppendTail(1); stQueue.AppendTail(2); stQueue.AppendTail(3); cout << "Queue Pop Node: " << stQueue.DeleteHead() << endl; stQueue.AppendTail(4); stQueue.AppendTail(5); stQueue.AppendTail(6); cout << "Queue Pop Node: " << stQueue.DeleteHead() << endl; cout << "Queue Pop Node: " << stQueue.DeleteHead() << endl; cout << "Queue Pop Node: " << stQueue.DeleteHead() << endl; cout << "Queue Pop Node: " << stQueue.DeleteHead() << endl; cout << "Queue Pop Node: " << stQueue.DeleteHead() << endl; cout << "\n\n --------------- QueueWithTwoStackTestFunc End -------------->" << endl;}
/
// 11.用两个队列实现一个栈templateclass CStack{public: CStack(){} ~CStack(){}public: void AppendTail(const TYPE& value); TYPE DeleteHead();private: queue m_stQueue1; queue m_stQueue2;};template TYPE CStack ::DeleteHead(){ TYPE head; if (m_stQueue1.empty()) { while (m_stQueue2.size() > 1) { m_stQueue1.push(m_stQueue2.front()); m_stQueue2.pop(); } head = m_stQueue2.front(); m_stQueue2.pop(); } else { while (m_stQueue1.size() > 1) { m_stQueue2.push(m_stQueue1.front()); m_stQueue1.pop(); } head = m_stQueue1.front(); m_stQueue1.pop(); } return head;}template void CStack ::AppendTail(const TYPE& value){ m_stQueue1.push(value);}void StackWithTwoQueueTestFunc(){ cout << "\n\n --------------- StackWithTwoQueueTestFunc Start -------------->" << endl; CStack stStack; stStack.AppendTail(1); stStack.AppendTail(2); stStack.AppendTail(3); cout << "Stack Pop Node: " << stStack.DeleteHead() << endl; stStack.AppendTail(4); stStack.AppendTail(5); stStack.AppendTail(6); cout << "Stack Pop Node: " << stStack.DeleteHead() << endl; cout << "Stack Pop Node: " << stStack.DeleteHead() << endl; cout << "Stack Pop Node: " << stStack.DeleteHead() << endl; cout << "Stack Pop Node: " << stStack.DeleteHead() << endl; cout << "Stack Pop Node: " << stStack.DeleteHead() << endl; cout << "\n\n --------------- StackWithTwoQueueTestFunc End -------------->" << endl;}