您的位置:首页 > 其它

两个栈实现一个队列

2016-06-24 18:48 316 查看
栈的特点:

先进后出

队列特点:

先进先出

实现方法:

定义两个栈,在插入队列的时候往栈1中插入,在删除的时候先把栈1的数据全部插入到栈2中,然后删除栈2顶部的元素,这样就可以实现先出的功能。

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

template<class T>
class Queue
{
public:
void Push(const T& x)
{
_stack1.push(x);
}
void Pop()
{
if (_stack2.size() <= 0)
{
if (!_stack1.empty())
{
T& data = _stack1.top();
_stack1.pop();
_stack2.push(data);
}

}
if (_stack2.empty())
{
cout << "queue is empty!" << endl;
return;
}
_stack2.pop();
}

private:
stack<T> _stack1;
stack<T> _stack2;
};

void test()
{
Queue<int> q;
q.Push(1);
q.Push(2);
q.Push(3);
q.Push(4);
q.Push(5);
q.Pop();
q.Pop();
q.Pop();
q.Pop();
q.Pop();
}

int main()
{
test();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息