用两个队列实现栈&用两个栈实现队列

所谓栈:通常简单的栈使用线性表实现的,只是在push或者pop的时候要遵循它的“先入后出”的规则就是栈。

所谓队列:通常简单的队列也是由线性表实现的,只是在push或者pop的时候要遵循它的“先入先出”的规则。

如图所示:

以下的实现中另一个队列或者栈都作为一个临时的对象来做暂时的保存数据,以便恢复被操作后的队列或栈。 

 两个队列实现栈

class queueStack
{
	queue<int> m_qu1;
public:
	queueStack()
	{

	}

	void push(int x)
	{
		m_qu1.push(x);
	}

	void pop()
	{
		queue<int> m_qu2;
		while (m_qu1.size() > 1)
		{
			m_qu2.push(m_qu1.front());
			m_qu1.pop();
		}
		m_qu1 = m_qu2;
	}

	int top()
	{
		queue<int> m_qu2;
		while (m_qu1.size() > 1)
		{
			m_qu2.push(m_qu1.front());
			m_qu1.pop();
		}
		int tmp = m_qu1.front();
		m_qu2.push(m_qu1.front());
		m_qu1 = m_qu2;
		return tmp;
	}
};

两个栈实现队列(模板类)

#include <iostream>
#include <stack>
using namespace std;
template<class T>
class stacktoquueu 
{
	stack<T> m_stk1;
public:
	stacktoquueu()
	{

	}
	void qu_push(T x)
	{
		m_stk1.push(x);
	}
	void qu_pop()
	{
		/* 队列的删除是从队头删 */
		stack<T> m_stk2;
		while (m_stk1.size()>1)
		{
			m_stk2.push(m_stk1.top());
			m_stk1.pop();
		}
		m_stk1.pop();
		while (m_stk2.size())
		{
			m_stk1.push(m_stk2.top());
			m_stk2.pop();
		}
	}
	T qu_front()
	{
		/* 取队列的头 */
		stack<T> m_stk2;
		while (m_stk1.size() > 1)
		{
			m_stk2.push(m_stk1.top());
			m_stk1.pop();
		}
		int tmp = m_stk1.top();

		while (m_stk2.size())
		{
			m_stk1.push(m_stk2.top());
			m_stk2.pop();
		}
		return tmp;
	}
	T qu_back()
	{
		return m_stk1.top();
	}

};
int main()
{
	stacktoquueu<int> qu;
	qu.qu_push(1);
	qu.qu_push(2);
	qu.qu_push(3);
	qu.qu_push(4);
	qu.qu_pop();
	qu.qu_pop();
	qu.qu_push(5);
	cout << qu.qu_front() << ' ' << qu.qu_back() << endl;
	system("pause"); 
	return 0;
}

EOF

发布了157 篇原创文章 · 获赞 98 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43447989/article/details/102478894