用两个队列实现栈和用两个栈实现队列
来源:互联网 发布:ubuntu 查看mysql 编辑:程序博客网 时间:2024/05/24 04:48
用两个栈实现队列的功能:
//用两个栈实现队列//栈:后进先出//队列:先进先出//用一个栈s1来保存数据,当数据要出队列的时候,先判断栈s2是否为空//若为空,则将栈s1中的数据都压入栈s2中再pop,若为非空,则直接从栈s2中pop数据#include<stdio.h>#include<stack>#include<queue>#include<stdlib.h>#include<iostream>using namespace std;template<class T>class Queue{public:Queue(){}~Queue(){}void Push(T data);void Pop();private:stack<T> s1;stack<T> s2;};template<class T>void Queue<T>::Push(T data){s1.push(data);}template<class T>void Queue<T>::Pop(){if (s2.empty()){while (!s1.empty()){T temp = s1.top();s1.pop();s2.push(temp);}}s2.pop();}
//用两个队列实现一个栈template<class T>class Stack{public:Stack(){}~Stack(){}void Push(T data);void Pop();private:queue<T> q1;queue<T> q2;};template<class T>void Stack<T>::Push(T data){q1.push(data);}template<class T>void Stack<T>::Pop(){if (!q1.empty() && q2.empty()){while (q1.size() != 1){T ret = q1.front();q1.pop();q2.push(ret);}q1.pop();}else if (q1.empty() && !q2.empty()){while (q2.size() != 1){T ret = q2.front();q2.pop();q1.push(ret);}q2.pop();}else{return;}}
阅读全文
0 0
- 用两个栈实现队列 & 用两个队列实现栈
- 用两个队列实现栈&用两个栈实现队列
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 团战可以输、提莫必须死
- 冒泡排序
- Java8种排序算法学习
- Java数组、遍历数组
- Redis:存储对象的两种方式(序列化和json字符串)
- 用两个队列实现栈和用两个栈实现队列
- 51nod 1267 4个数和为0
- public class Solution { public int countPrimes(int n) { boolean[] isDelArray = new boolean[n];
- PowerDesigner中NAME和COMMENT的互相转换,需要执行语句
- 动/静态接收系统广播
- Mysql 表设计
- Socket的简单数据传递
- CreateProcessAsUser常用参数说明
- Dinic最大流(bzoj 2756: [SCOI2012]奇怪的游戏)