漫步者s1000功放ic:请问怎样用两个栈实现一个队列?最好给出算法谢谢

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/28 10:18:38

示例程序如下,其中TMyQueue就是用栈实现的队列:
#include <iostream>
#include <stack>

class TMyQueue
{
private:
stack<char> s1,s2;
public:
void push(char c)
{
while (!s2.empty())
{
char x = s2.top();
s2.pop();
s1.push(x);
}
s1.push( c );
}
char pop()
{
char c;
while (!s1.empty())
{
char x = s1.top();
s1.pop();
s2.push(x);
}
c = s2.top();
s2.pop();
return c;
}
bool empty() const
{
return s1.empty() && s2.empty();
}
};

int main()
{
TMyQueue q;
int i;
char buf1[4] = "one";
char buf2[4] = "two";
char buf3[6] = "three";
for (i = 0; i < 3; i++)
q.push(buf1[i]);
for (i = 0; i < 3; i++)
q.push(buf2[i]);
for (i = 0; i < 3; i++)
cout << q.pop();
cout << endl;
for (i = 0; i < 5; i++)
q.push(buf3[i]);
while (!q.empty())
{
cout << q.pop();
}
cout << endl;
return 0;
}

运行结果:
one
twothree

先将数组压入一栈中,然后再弹出到别一个栈中,这时的顺序不就是队列了吗?