两个栈实现一个队列
2016-06-24 18:48
316 查看
栈的特点:
先进后出
队列特点:
先进先出
实现方法:
定义两个栈,在插入队列的时候往栈1中插入,在删除的时候先把栈1的数据全部插入到栈2中,然后删除栈2顶部的元素,这样就可以实现先出的功能。
先进后出
队列特点:
先进先出
实现方法:
定义两个栈,在插入队列的时候往栈1中插入,在删除的时候先把栈1的数据全部插入到栈2中,然后删除栈2顶部的元素,这样就可以实现先出的功能。
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; #include<stack> template<class T> class Queue { public: void Push(const T& x) { _stack1.push(x); } void Pop() { if (_stack2.size() <= 0) { if (!_stack1.empty()) { T& data = _stack1.top(); _stack1.pop(); _stack2.push(data); } } if (_stack2.empty()) { cout << "queue is empty!" << endl; return; } _stack2.pop(); } private: stack<T> _stack1; stack<T> _stack2; }; void test() { Queue<int> q; q.Push(1); q.Push(2); q.Push(3); q.Push(4); q.Push(5); q.Pop(); q.Pop(); q.Pop(); q.Pop(); q.Pop(); } int main() { test(); system("pause"); return 0; }
相关文章推荐
- 两个栈实现一个队列
- 两个栈实现一个队列
- 运用两个栈实现队列
- 使用两个栈实现一个队列
- 简简单单学会C#位运算
- 英国退出欧盟,欧盟还是欧盟吗?
- 软件工程学习体会
- Python即时网络爬虫项目启动说明
- 数据包在用户空间的状态
- JS实现多少小时前,多少天前...
- 从 Poisson 分布到服务器的访问
- XJOI网上同步训练DAY1 T3
- LBP算法(人脸识别特征提取)
- 自定义View系列教程04--Draw源码分析及其实践
- TabLayout控件的使用(一)
- API指南之应用清单文件
- 事件系统
- MySql中,复制旧表结构到新表
- Oracle包编译,调用或调试Package时卡死问题
- 当REST遇上Java