Two stacks to achieve a C ++ code queue

       Use two stacks to implement a queue, this problem is very common. The key is to have a good idea, as to achieve, it is a very simple matter. In this article, also like to say that their own ideas, but I think the code used to express ideas more in line with my habit, is my food, so just shows the code. If necessary, we can come to understand the idea according to the code.

#include <iostream>
#include <stack>
using namespace std;
 
 
// 用两个stack实现一个queue, 以int类型为例吧
class MyQueque
{
private:
	stack<int> s1; // s1负责入队
	stack<int> s2; // s2负责出队
	
public:
	// 入队
	void push(int x)
	{
		s1.push(x);
	}
 
	// 出队
	void pop()
	{
		if(!s2.empty())
		{
			s2.pop();
		}
		else
		{
			while(!s1.empty())
			{
				int tmp = s1.top();
				s1.pop();
				s2.push(tmp);
			}
 
			s2.pop();
		}
	}
 
	// 取头
	int front()
	{
		if(!s2.empty())
		{
			return s2.top();
		}
 
		while(!s1.empty())
		{
			int tmp = s1.top();
			s1.pop();
			s2.push(tmp);
		}
 
		return s2.top();
	}
 
	// 取尾
	int back()
	{
		if(!s1.empty())
		{
			return s1.top();
		}
 
		while(!s2.empty())
		{
			int tmp = s2.top();
			s2.pop();
			s1.push(tmp);
		}
 
		return s1.top();
	}
 
	// 求大小
	int size()
	{
		return s1.size() + s2.size();
	}
 
	// 判断是否为空
	bool empty()
	{
		if(s1.empty() && s2.empty())
		{
			return true;
		}
 
		return false;
	}
};
 
 
int main()
{
	{
		MyQueque que;
		que.push(1);
		que.push(2);
		que.push(3);
		que.push(4);
		que.push(5);
 
		while(!que.empty())
		{
			cout << que.front() << endl;
			que.pop();
		}
 
		cout << "-------------------" << endl;
	}
 
 
	{
		MyQueque que;
		que.push(1);
		que.push(2);
		que.push(3);
		que.push(4);
		que.push(5);
 
		while(!que.empty())
		{
			cout << que.size() << endl;
			que.pop();
		}
 
		cout << "-------------------" << endl;
	}
 
 
	{
		MyQueque que;
		que.push(1);
		que.push(2);
		que.push(3);
		que.pop();
		que.pop();
		que.push(4);
		que.push(5);
 
		while(!que.empty())
		{
			cout << que.front() << endl;
			que.pop();
		}
 
		cout << "-------------------" << endl;
	}
 
	return 0;
}

 

Published 407 original articles · won praise 150 · views 380 000 +

Guess you like

Origin blog.csdn.net/ds1130071727/article/details/103374871