您的位置:首页 > 职场人生

记一道面试题:STL两个栈实现一个队列。

2018-03-20 19:54 260 查看

面试题目

STL两个栈实现一个队列。
要求:只能使用栈的pop(),top()和push(),以及测试栈是否为空empty()四个操作. 来实现队列的clear(), push(),pop(),back(),front()等操作。

思路解析

用一个栈用作队列的容器,另一个栈用作临时容器,由于队列 具有先进先出的特性,而我们的栈 只有一端可以进出,那么我们在做出队,也就是 要将一个栈的栈底元素 出队,所以要用到另一个栈作为临时容器

代码展示

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stack>
using namespace std;
template<class T>
class MyQueue
{
//对外接口
public:
//清空队列
void clear()
{
s.clear();
temp.clear();
}
//入队
void push(T data)
{
s.push(data);
}
//出队,删除栈底元素
T pop()
{
while (!s.empty())
{
T t= s.top();
s.pop();
temp.push(t);
}
T del = temp.top();
temp.pop();//元素出队
//将数据 还原
while (!temp.empty())
{
T t = temp.top();
temp.pop();
s.push(t);
}
return del;
}
//队尾,也是栈顶元素
T back()
{
return s.top();
}
//队头,也就是栈底元素
T front()
{
while (!s.empty())
{
T t = s.top();
s.pop();
temp.push(t);
}
T frontEle = temp.top();
//将数据 还原
while (!temp.empty())
{
T t = temp.top();
temp.pop();
s.push(t);
}
return frontEle;
}
private:
stack<T> s;	//充当队列的容器
stack<T> temp;//临时容器
};
/*
STL两个栈实现一个队列。

要求:只能使用栈的pop(),top()和push(),以及测试栈是否为空
empty()四个操作. 来实现队列的clear(), push(),pop(),back(),front()等操作。
*/
int main(int argc, char *argv[])
{
MyQueue<int> que;
que.push(1);
que.push(2);
que.push(3);
// 出队<-  1  2  3 <-入队
cout << que.front() << endl;//1
cout << que.back() << endl;	// 3

cout << que.pop() << endl;//1
cout << que.pop() << endl;//2
cout << que.pop() << endl;//3

que.clear();

return EXIT_SUCCESS;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: