C++用两个栈实现一个队列

下面两幅图分别是栈和队列的简单介绍:
在这里插入图片描述

1.push(入队)

在这里插入图片描述

入队时,给stack1入相同的数据。

2.pop(出队)

在这里插入图片描述

1.先将 stack1 栈顶的数据入栈到 stack2 中,每次 pop 掉 stack1 中的数据,直至 stack1.size()==1为止。
2.再将 stack2 中的数据出栈进 stack1 中。

3.代码实现

#include<iostream>
#include<stack>
using namespace std;

template<class T>
class Queue
{
private:
	stack<T> st1;
public:
	void push(T x)
	{
		st1.push(x);
	}

	void pop()
	{
		stack<T> tmp;
		stack<T> st2;

		while (st1.size() > 1)
		{
			st2.push(st1.top());//将st1中的数据逆序入栈进st2
			st1.pop();
		}
		st1.pop();//将st1清空;

		while (!st2.empty())
		{
			st1.push(st2.top());//再将st2的数据逆序入栈进st1,此时的st1已经pop掉第一个元素。
			st2.pop();
		}
	}

	T& front()
	{
		T res;
		stack<T> tmp;
		tmp = st1;

		while (st1.size() > 1)
		{
			st1.pop();
		}
		res = st1.top();//记录front的值

		st1 = tmp;
		return res;
	}

	T& back()
	{
		return st1.top();
	}

	bool empty()
	{
		return st1.empty();
	}

	size_t size()
	{
		return st1.size();
	}

};
int main()
{
	Queue<int> qu;
	qu.push(1);
	qu.push(2);
	qu.pop();
	cout << qu.front() << endl;
	qu.push(3);
	qu.push(4);
	qu.push(5);
	qu.pop();
	cout << qu.back() << " " << qu.front() << endl;
	system("pause");
	return 0;
}
发布了77 篇原创文章 · 获赞 16 · 访问量 6535

猜你喜欢

转载自blog.csdn.net/weixin_43886592/article/details/102484824