您的位置:首页 > 其它

使用两个栈实现一个队列

2016-06-11 18:53 357 查看
面试题:用两个栈(Stack)实现一个队列(Queue)
思路:
1、入队时,将元素压入s1。
2、出队时,判断s2是否为空,如不为空,则直接弹出顶元素;如为空,则将s1的元素逐个“倒入”s2,把最后一个元素弹出并出队。
这个思路,避免了反复“倒”栈,仅在需要时才“倒”一次。
650) this.width=650;" src="http://s5.51cto.com/wyfs02/M01/7F/01/wKioL1cPpw_gNRQzAAAyBsdXVjE289.png" title="无标题.png" alt="wKioL1cPpw_gNRQzAAAyBsdXVjE289.png" />
具体实现如下:
测试用例如下:
void Test2()
{
//Queue<int> q1;
//q1.s1.push(3);
//q1.s2.push(4);
//q1.s2.push(5);
//q1.Push(2);
//q1.Push(1);
//q1.PrintQueue();
////q1.Pop();
////q1.Pop();
////q1.Pop();
////q1.Pop();
////q1.Pop();
////q1.Pop();
////q1.PrintQueue();

Queue<string> q1;
q1.s1.push("lllll");
q1.s2.push("yyyyy");
q1.s2.push("fffff");
q1.Push("xxxxx");
q1.Push("yyyyy");
q1.PrintQueue();
cout << "empty: " << q1.Empty() << endl;
cout << "size: " << q1.Size() << endl;
cout << "front: " << q1.Front() << endl;
cout << "back: " << q1.Back() << endl;
}
本文出自 “Scen” 博客,请务必保留此出处http://10741357.blog.51cto.com/10731357/1763949
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: