您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
数据结构用两个栈实现一个队列的实例
栈是先进后出,队列是先进先出
每次元素都push在st1中,pop的时候如果st2为空,将st1的栈顶元素放在st2的栈底,这样st1的所有元素都放在st2中,st1的栈底就是st2的栈顶,pop st2的栈顶,这样就满足了队列的先进先出。

#include <iostream>
using namespace std;
#include <stack>
#include <stdlib.h>
template <class T>
class SQueue {
public:
void Push(const T& value);
T Pop();
private:
stack<T> st1;
stack<T> st2;
};
template <class T>
T SQueue<T>::Pop()
{
if (st2.size() <= 0)
{
if (st1.size() == 0)
{
exit(1);
}
while ((st1.size() > 0))
{
T& top = st1.top();
st2.push(top);
st1.pop();
}
}
T head = st2.top();
st2.pop();
return head;
}
template <class T>
void SQueue<T>::Push(const T& value)
{
st1.push(value);
}
int main()
{
SQueue<int> sq;
for (int i = 0; i < 10; ++i)
{
sq.Push(i);
}
for (int i = 0; i < 5; ++i)
{
cout << sq.Pop() << " ";
}
for (int i = 0; i < 5; ++i) //分两次验证
{
cout << sq.Pop() << " ";
}
cout << endl;
system("pause");
return 0;
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。