c ++ realize a stack with two queues

/ *
Title: two queues implemented by a stack
algorithm idea:
the two existing queue q1 and q2, the stack: if q1 and q2 are empty, so we chose q1 push into the queue is, for example, q1 stack 1 234; now out of the stack, LIFO then 4 to the stack. However, q1 is a
queue FIFO, then the queue 123 queues Q2 123, the remaining 4 q1 in this case, the four pairs of columns from the stack to achieve the effect. This time if we add an element to 5, then we should put 5 into
q1 or q2, because there are now 1 2 3 q2, q1 inconvenient to statistics put the 5, so 5 should put to q2; if 5 put q1, wait for the next write code stack a lot of trouble, if we only need to be classified into q2: q2
is not empty, as empty as a case, not empty is a situation:
so in the end:
if q1 and q2 are empty, then the element is inserted into q1
if q1 is not empty, then inserting the element into the q1
if q2 is not empty, then the element is inserted into q1
* /

#include "stdio.h"
#include <iostream>
#include <queue>
using namespace std;

template<typename T>

class CStack
{
private:
	queue<T> q1;
	queue<T> q2;
	int nCount;//用来统计队列中有几个元素,只有队列中元素剩余一个时,才能实现后进先出的功能(栈)


public:
	void appendTail(const T& data);
	T deleteTail();
	int GetNum() const;
	CStack()
	{
		nCount = 0;
	}
};

template<typename T>
int CStack<T>::GetNum() const
{
	return nCount;
}

template<typename T>
void CStack<T>::appendTail(const T& data)
{
	//一直保证q1与q2有一个为空,比如q1如栈 1 2 3 4 ,现在要出栈4,那么把1 2 3 出队列q1让如队列q2,4出栈
	//之后,此时如果有加入一个元素,那么最后加到q2中。

	if (q1.size() == 0 && q2.size() == 0)//如果q1与q2都为空,那么往q1中插入元素
	{
		q1.push(data);
	}
	else if (q1.size()>0)//如果q1不为空,那么往q1中插入元素
	{
		q1.push(data);
	}
	else if (q2.size()>0)//如果q2不为空,那么往q1中插入元素
	{
		q2.push(data);
	}
	++nCount;
}

template<typename T>
T CStack<T>::deleteTail()
{
	T ret;
	if (q2.size() == 0)
	{

		while (q1.size() != 1)
		{
			T& data = q1.front();
			q1.pop();
			q2.push(data);
		}
		ret = q1.front();
		q1.pop();
		cout << ret << endl;
	}
	else
	{
		while (q2.size() != 1)
		{
			T& data = q2.front();
			q2.pop();
			q1.push(data);
		}
		ret = q2.front();
		q2.pop();
		cout << ret << endl;
	}
	--nCount;
	return ret;//返回删除的元素
}

int main()
{

	CStack<int> stack;
	stack.appendTail(88);
	stack.appendTail(44);
	stack.appendTail(99);
	cout << "元素的个数:" << stack.GetNum() << endl;//3
	cout << "出栈,后进先出:" << endl;//99
	stack.deleteTail();

	cout << "元素的个数:" << stack.GetNum() << endl;//2
	cout << "出栈,后进先出:" << endl;//44
	stack.deleteTail();

	stack.appendTail(777);//插入一个新的元素777
	cout << "元素的个数:" << stack.GetNum() << endl;//2
	cout << "出栈,后进先出:" << endl;//777
	stack.deleteTail();

	cout << "元素的个数:" << stack.GetNum() << endl;//1
	cout << "出栈,后进先出:" << endl;//88
	stack.deleteTail();

	return 0;
}

Reference Hirofumi: Https://Blog.Csdn.Net/djb100316878/article/details/41820953

Guess you like

Origin blog.csdn.net/yimixgg/article/details/92800007