用两个栈实现队列
来源:互联网 发布: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
- 用两个栈实现队列 & 用两个队列实现栈
- 用两个队列实现栈&用两个栈实现队列
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 利用GHUnit编写iOS单元测试
- 巴菲特2014年致股东信(中文)
- Awk笔记
- URL
- SRM 585
- 用两个栈实现队列
- 如何控制 Internet Explorer 浏览器的进程数量
- 采用服务监听用户的通话,上传信息到服务器
- Java多线程之可阻塞的队列
- 关于git-repo时manifest.xml的一些整理
- 关于java学习
- 数据库链接
- java 缓冲区
- CORS