C++俩队实现栈

自画草图:
在这里插入图片描述
在这里插入图片描述

设计思路:
1.q1入队
2.q1出队,除了队尾元素,出队的元素到入队q2中,q1队尾元素出队,即为弹栈
3.再调换两队,执行同样操作,直到q1队为空队

#include <iostream>
#include<queue>//系统队 
using namespace std;

class MyStack{
	public:
		queue<int> q1; 
		queue<int> q2;
	public:
		//压栈  即向q1入队
		void push(int ele){
			q1.push(ele);
		} 
		//出栈  
		void pop(int arrs[]){//数组盛放出栈的数据 
			int index = 0;
			while(!q1.empty()){//循环判断q1是否为空 
				if(q1.size() == 1){// 如果是1的话,证明这个队中只有一个元素即队尾元素,出栈 
					int ele = q1.front();//front是获取第一个元素 
					arrs[index] = ele;
					index++;
					q1.pop();	//出栈后,出队
					swap(q1,q2); //交换q1和q2 
				}else{
					int ele = q1.front();
					q1.pop();
					q2.push(ele);//把q1中除队尾元素之外的元素全部入队到q2 
				}
			}
		} 
};

int main(){
	MyStack s;
	s.push(10);
	s.push(8);
	s.push(6);
	cout<<"s.push(10)"<<endl;
	cout<<"s.push(8)"<<endl;
	cout<<"s.push(6)"<<endl;
	cout<<"s.pop():"<<endl;
	
	int len = s.q1.size();
	int arrs[len];
	
	s.pop(arrs);
	
	for(int &i : arrs){
		cout<<i<<" ";
	}

	return 0;
}

在这里插入图片描述

发布了167 篇原创文章 · 获赞 52 · 访问量 6928

猜你喜欢

转载自blog.csdn.net/qq_42363032/article/details/103846245