记一道面试题: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; }
相关文章推荐
- 面试题7:用两个栈实现队列和用两个队列实现一个栈
- C++面试题:两个队列实现一个栈
- 面试题7两个栈实现一个队列和两个队列实现一个栈
- 剑指offer面试题java实现之题7:用两个栈模拟一个队列的入队和出队操作
- 数据结构面试题(1)--用两个队列实现一栈和用两个栈实现一个队列
- 面试题 7: 两个栈实现一个队列
- 栈和队列面试题(三)---用两个队列实现一个栈
- 算法面试题:使用两个堆栈实现一个队列
- 【数据结构】(面试题)使用两个栈实现一个队列(详细介绍)
- 面试题:用两个队列实现一个栈
- 两个栈实现一个队列——栈和队列面试题(2)
- 【数据结构】(面试题)使用两个栈实现一个队列(详细介绍)
- 【面试题】剑指offer07--两个栈实现一个队列
- 栈和队列面试题(一)---一个数组实现两个栈
- 【数据结构】(面试题)使用两个栈实现一个队列(详细介绍)
- 数据结构面试题:两个队列实现一个堆栈
- 面试题7:用两个队列实现一个栈
- 面试题:用两个栈实现一个队列
- 58面试题-----用两个栈实现一个队列
- 剑指offer之面试题7用两个栈实现一个队列