面试题6:用两个栈实现队列
思路:设置两个栈stack1和stack2,stack1实现入队列功能,stack2实现出队列功能。
(1)入队列:入栈stack1
(2)出队列:若stack2不空,则直接弹出stack2中的栈顶元素
若stack2为空,则依次弹出stack1中的元素放入stack2中,再弹出stack2中的栈顶元素
C++代码:
#include "stdafx.h" #include <iostream> #include <stack> using namespace std; template<class T> class CQueue { public: CQueue(void); ~CQueue(void); void AddTail(const T &addData); void DeleteHead(T &deleteData); private: stack<T> stack1; stack<T> stack2; }; template<class T> CQueue<T>::CQueue(void) { } template<class T> CQueue<T>::~CQueue(void) { } template<class T> void CQueue<T>::AddTail(const T &addData) { stack1.push(addData); } template<class T> void CQueue<T>::DeleteHead(T &deleteData) { if (stack2.empty()) { while (!stack1.empty()) { T topData = stack1.top(); stack2.push(topData); stack1.pop(); } } if (stack2.empty()) { cout << "队列中无元素!" << endl; } else { deleteData = stack2.top(); stack2.pop(); } } int _tmain(int argc, _TCHAR* argv[]) { CQueue<int> q; for (int i=0; i<6; i++) { q.AddTail(i); } int deleteData = 0; for (int i=0; i<6; i++) { q.DeleteHead(deleteData); cout << deleteData << " "; } cout << endl; q.DeleteHead(deleteData); system("pause"); return 0; } #include "stdafx.h" #include <iostream> #include <stack> using namespace std; template<class T> class CQueue { public: CQueue(void); ~CQueue(void); void AddTail(const T &addData); void DeleteHead(T &deleteData); private: stack<T> stack1; stack<T> stack2; }; template<class T> CQueue<T>::CQueue(void) { } template<class T> CQueue<T>::~CQueue(void) { } template<class T> void CQueue<T>::AddTail(const T &addData) { stack1.push(addData); } template<class T> void CQueue<T>::DeleteHead(T &deleteData) { if (stack2.empty()) { while (!stack1.empty()) { T topData = stack1.top(); stack2.push(topData); stack1.pop(); } } if (stack2.empty()) { cout << "队列中无元素!" << endl; } else { deleteData = stack2.top(); stack2.pop(); } } int _tmain(int argc, _TCHAR* argv[]) { CQueue<int> q; for (int i=0; i<6; i++) { q.AddTail(i); } int deleteData = 0; for (int i=0; i<6; i++) { q.DeleteHead(deleteData); cout << deleteData << " "; } cout << endl; q.DeleteHead(deleteData); system("pause"); return 0; }
补充:软件开发 , C++ ,