使用两个栈实现一个队列
队列的特点是先进先出,根据这个可以有如下示意图:
栈s1用来入数据,栈s2用来出数据;当s1入数据之后需要判断s2是否为空,为空的时候才可以将栈s1中的数据压入进去,当栈s1为空的时候,将栈s2的数据输出,输出后数据的顺序和队列入栈出栈的效果相同。
要实现一个队列就要实现其基本的接口:
Push(入队列),Pop(出队列),Front(队头节点),Size(队列的元素个数),Empty(判空)。
#include<iostream>
#include<stdlib.h>
#include<stack>
#include<queue>
using namespace std;
template<class T>
class QueueByStack
{
public:
stack<T> s1;//压队列元素入栈
stack<T> s2;//使队列元素出栈
void Push(const T& x)
{
s1.push(x);//将元素压入栈s1
}
void Pop()
{
//当栈s2为空的时候,直接将s1里面的元素输出压入s2中,取栈s2的头节点输出,再将其pop。
if (s2.empty())
{
while (!s1.empty())
{
T cur = s1.top();
s2.push(cur);
s1.pop();
}
}
cout << s2.top() << " ";
s2.pop();
}
//队列队头的元素
T& Front()
{
if (s2.empty())
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
//队列的队头
T Size()
{
return s1.size() + s2.size();
}
//队列的判空
bool Empty()
{
return (s1.empty() && s2.empty());
}
};
int main()
{
QueueByStack<int> Q;
Q.Push(1);
Q.Push(2);
Q.Push(3);
Q.Push(4);
cout << Q.Front() << endl;
cout << Q.Size() << endl;
Q.Pop();
Q.Pop();
Q.Pop();
Q.Pop();
cout << endl;
system("pause");
}
使用两个队列实现一个栈
根据队列的性质实现栈示意图如下:
先将数据输入到空队列q1和q2任意一个中,接着将有数据的队列中的元素依次输入到空队列中,注意,剩下最后一个元素并输出;继续执行上述操作,知道两个队列中元素为空。
实现一个栈的基本接口:
Push(入栈),Pop(出栈),Top(栈头节点),Size(栈的元素个数),Empty(判空)。
template<class T>
class StackByQueue
{
public:
queue<T> q1;
queue<T> q2;
void Push(const T& x)//压入数据
{
if (!q1.empty())//不为空的执行添加数据
{
q1.push(x);
}
else
{
q2.push(x);
}
}
void Pop()//出数据
{
//当有一个队列为空,一个队列不为空的时候,要将队列不为空的数据
//压入到空队列中,只剩下最后一个数据,输出,在做重复的调换即可
if (q1.empty())
{
int count = q2.size();
while (count != 1)//保证了不为空的队列可以剩下一个元素
{
q1.push(q2.front());
q2.pop();
--count;
}
cout << q2.front()<<" ";
q2.pop();
}
else
{
int count = q1.size();
while (count != 1)
{
q2.push(q1.front());
q1.pop();
--count;
}
cout << q1.front()<<" ";
q1.pop();
}
}
//返回栈的栈顶元素
T& Top()
{
if (q1.empty())
{
int count = q2.size();
while (count != 1)
{
q1.push(q2.front());
q2.pop();
--count;
}
return q2.front();
}
else
{
int count = q1.size();
while (count != 1)
{
q2.push(q1.front());
q1.pop();
--count;
}
return q1.front();
}
}
//栈的元素个数
T Size()
{
return q1.size() + q2.size();
}
//栈的判空操作
bool Empty()
{
return (q1.empty() && q2.empty());
}
};
int main()
{
StackByQueue<int> S;
S.Push(1);
S.Push(2);
S.Push(3);
S.Push(4);
S.Push(5);
cout << S.Size() << endl;
//cout << S.Top() << endl;
S.Pop();
S.Pop();
S.Pop();
S.Pop();
S.Pop();
cout << endl;
system("pause");
}