用两个队列实现栈和用两个栈实现队列

来源:互联网 发布: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;}}



原创粉丝点击