栈结构:先进后出,后进先出,只容许在栈尾操做。ios
队列:先进先出,在队尾入队,在队头出队。ide
要想用两个栈实现一个队列,就须要使用一个至关于中间量的结构进行队列的入队和出队操做。函数
用图形象化为:spa
这样问题就从图中得出了思路:3d
入队操做:把入队元素一一存入一个栈结构中便可。blog
出队操做:出队时,先判断另外一个栈结构中是否有元素,如有先将元素出栈Pop();若为空,则把栈S1中的元素所有倒入Push()栈S2中,而后让S2栈顶元素出栈Pop(),此时的元素序列和栈S1中恰好相反,即达到出队效果。队列
那么,用代码实现也变得简单:get
#include <iostream> #include <stack> using namespace std; class Queue { public: void Push_Queue(int val) { s1.push(val); // 实现了入队尾入队操做 cout <<s1.top() << " "; } void Pop_Queue() { if (s2.empty()) { while (s1.top()) { s2.push(s1.top()--); } s2.pop(); // 实现了队头出队操做 } else { s2.pop(); } } void Show() { cout << endl; // 由于使用的是系统库stack,其pop函数返回值为void,因此不能打印出来,咱们只打印pop后的队头元素进行验证 cout << s2.top() << endl; } private: stack<int> s1; stack<int> s2; }; int main() { Queue q; // ??构造函数的参数 q.Push_Queue(1); q.Push_Queue(2); q.Push_Queue(3); q.Push_Queue(4); q.Push_Queue(5); q.Pop_Queue(); q.Show(); // 打印pop后的对头元素 system("pause"); return 0; }
若有纰漏,欢迎指正。
it