C ++コードのキューを達成するために2つのスタック

       キューを実装するために2つのスタックを使用して、この問題は非常に一般的です。キーは、それは非常に単純な問題である、達成するように、良いアイデアを持っていることです。また、のようなこの記事では、自分のアイデアが、私は私の習慣に沿って、より多くのアイデアを表現するために使用されるコードを考えると言うことで、これだけのコードを示して、私の食べ物です。必要であれば、私たちはコードに応じて考えを理解するために来ることができます。

#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;
}

 

公開された407元の記事 ウォンの賞賛150 ビュー380 000 +

おすすめ

転載: blog.csdn.net/ds1130071727/article/details/103374871