栈与队列的相互转换实现

一、使用两个栈实现一个队列(栈s1,s2)

入队操作:入栈操作,count+1;

出队操作:s1出栈,入栈s2,出栈s2

具体实现代码:

#include<iostream>
#include<stack>
using namespace std;
//利用两个栈实现一个队列
template<class T>
class MyQue{
private:
	int count;
	stack<T> s1;
	stack<T> s2;
public:
	MyQue():count(0){}
	void push(T elem){
		s1.push(elem);
		cout<<"入队元素为:"<<elem<<endl;
		count++;
	}
	void change(){//将栈转化成队列的成员函数
	   for(int i=0;i<count;i++){
		  T tmp=s1.top();
		  s1.pop();
		  s2.push(tmp);
		}
	}
	void pop(){
		cout<<"队首元素为"<<s2.top()<<endl;
		s2.pop();
		count--;
	}
};
int main(){
	MyQue<int> q;
	for(int i=0;i<5;i++){
		q.push(i);
	}
	q.change();
	for(int j=0;j<5;j++){
		q.pop();}
	system("pause");
	return 0;
}

运行结果:

二、使用队列来实现栈

入栈操作:入队操作

出栈操作:将前count-1个元素先出队再入队,最终将队尾元素移到了队首,就可以出队啦

实现代码:

#include <iostream>
#include <queue>
#include <list>
#include <deque>
using namespace std;
template<class T>
class MyStack{
private:	
	int count;
    queue<T> MyQueue;
public:
	MyStack():count(0){}
	void Push(T elem){
		MyQueue.push(elem);
		count++;
	}
	void Pop(){//出栈操作,先将前n-1个元素出队,再入队,最后再执行一次让第n的元素出队
	   int i;
	   T tmp;
	   for(i=0;i<count-1;i++){
		   tmp=MyQueue.front();
		   MyQueue.pop();
		   MyQueue.push(tmp);
	   }
	   MyQueue.pop();
	   count--;
	}
	int top(){
		return MyQueue.back();
	}
};
int main(){
	MyStack<int> s;//创建类的对象
	int num;
	for(int i=1;i<5;i++){
	 s.Push(i);
	}
	for(int j=1;j<5;j++){
	 num=s.top();
	 s.Pop();
	 cout<<"栈顶元素为"<<num<<endl;;
	}
	system("pause");
	return 0;	
}

实现结果:

猜你喜欢

转载自blog.csdn.net/qq_40170007/article/details/88079042