用两个栈实现队列

来源:互联网 发布:2017淘宝排名规则 编辑:程序博客网 时间:2024/06/18 08:00

 

/****************************************************题目:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。template<typename T> class CQueue{public:CQueue(void);~CQueue(void);void appendTail(const T& node);T deleteHead();private:stack<T> stack1;stack<T> stack2;};****************************************************/#include<iostream>#include<stack>using namespace std;template<typename T> class CQueue{public:CQueue(void);~CQueue(void);void appendTail(const T& node);T deleteHead();private:stack<T> stack1;stack<T> stack2;};template<typename T>CQueue<T>::CQueue(){}template<typename T>CQueue<T>::~CQueue(){}template<typename T>void CQueue<T>::appendTail(const T& node){stack1.push(node);}template<typename T>T CQueue<T>::deleteHead(){T temp;if(stack2.empty()){while(!stack1.empty()){temp = stack1.top();stack2.push(temp);stack1.pop();}}if(stack2.empty())throw new exception("queue is empty!");temp = stack2.top();stack2.pop();return temp;}void test(){CQueue<char> charQueue;char temp;charQueue.appendTail('a');charQueue.appendTail('b');charQueue.appendTail('c');temp = charQueue.deleteHead();printf("%c\t",temp);temp = charQueue.deleteHead();printf("%c\t",temp);charQueue.appendTail('d');temp = charQueue.deleteHead();printf("%c\t",temp);temp = charQueue.deleteHead();printf("%c\t",temp);}int main(){test();return 0;}

/*
向stack1添加元素,删除时如果stack2有数据,直接从stack2中删除,
如果没有,则先从stack1中将数据全部放入stack2,然后再从stack2
中删除数据。

用两个队列实现一个栈。可以先将n个数据放入任一个队列中,当要弹出数据数,
可以将队列中n-1个数据放入另外一个队列中,把最后一个数据弹出;当再要放
数据时,将数据放到右数据的那个队列中。
*/

0 0
原创粉丝点击