【data structure】之栈与队列
来源:互联网 发布:wps登录显示网络异常 编辑:程序博客网 时间:2024/06/06 16:51
问题一:用两个队列实现一个栈
思路:
定义两个队列分别为q1,q2。
调用栈的push操作时,直接将元素push到队列q1中,时间复杂度为O(1)。
调用栈的pop操作时,先把q1中的q1.size() - 1个元素push到q2中,然后再pop出q1中的最后一个元素,再把q2中的所有元素全部push到q1中,时间复杂度为O(n)。
代码:
template<typename T>class Stack{queue<T> q1;queue<T> q2;public:void push(T i){q1.push(i);}void pop(){while (q1.size() > 1){q2.push(q1.front());q1.pop();}cout << q1.front() << endl;q1.pop();while (q2.size() > 0){q1.push(q2.front());q2.pop();}}};
问题二:用两个栈实现一个队列
思路:
定义两个栈分别为s1,s2。
调用队列的push操作时,直接将元素push到队列s1中,时间复杂度为O(1)。
调用队列的pop操作时,先把s1中的所有元素push到s2中,然后再调用s2的pop操作,再把s2中的所有元素全部push到s1中,时间复杂度为O(n)。
代码:
template<typename T>class Queue{stack<T> s1;stack<T> s2;public:void push(T i){s1.push(i);}void pop(){while (!s1.empty()){s2.push(s1.top());s1.pop();}cout << s2.top() << endl;s2.pop();while (!s2.empty()){s1.push(s2.top());s2.pop();}}};
- 【data structure】之栈与队列
- 【Data Structure】堆与优先队列
- HDU5929 Basic Data Structure(双端队列)
- UVA - 11995 - I Can Guess the Data Structure!(栈、队列、优先队列)
- UVA 11995 I Can Guess the Data Structure!【栈+队列+优先队列基本用法】
- 双端队列+与非运算——Basic Data Structure ( HDU 5929 )
- [Data Structure Primary][stack and queue]Rujia Liu-6.1.12-铁轨-栈和队列应用2
- Data Structure
- Data structure
- Data Structure
- Data structure
- Data structure
- data structure
- Data Structure
- Data structure
- Data Structure
- Data Structure
- Data Structure
- sicily 1159
- 从文件读入数据块时用feof(fp)判断文件结尾真的保险吗?
- 基于PHP的cURL快速入门(1)
- IOS开发之---静态库的编译以及相关问题的处理
- 谈谈O/R Mapping
- 【data structure】之栈与队列
- 推荐视觉跟踪领域的几个研究者
- 基于PHP的cURL快速入门(2)
- 基于PHP的cURL快速入门(3)
- 基于PHP的cURL快速入门(4)
- jQuery最佳实践
- 基于PHP的cURL快速入门(5)
- 扩展点总结之org.eclipse.ui.importWizards
- 分布式 Key-Value 存储系统:Cassandra 入门