【题目】
编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。
【解答】
队列是先进先出,栈是先进后出,那么一个栈存数据,
一个栈倒腾数据,当要弹出数据时,将数据栈倒腾到辅助栈,
然后弹出辅助栈的栈顶,再次入栈则直接压入数据栈,弹出则弹出辅助栈顶,
一旦辅助栈为空,则将数据栈倒腾数据进辅助栈,切记,数据栈只压入数据,而辅助栈只弹出数据
1 #include <iostream> 2 #include <queue> 3 #include <stack> 4 5 using namespace std; 6 7 8 //队列是先进先出,栈是先进后出,那么一个栈存数据, 9 //一个栈倒腾数据,当要弹出数据时,将数据栈倒腾到辅助栈, 10 //然后弹出辅助栈的栈顶,再次入栈则直接压入数据栈,弹出则弹出辅助栈顶, 11 //一旦辅助栈为空,则将数据栈倒腾数据进辅助栈,切记,数据栈只压入数据,而辅助栈只弹出数据 12 13 class StackToQueue 14 { 15 private: 16 stack<int>DataPush, DataPop; 17 18 public: 19 void Push(int a) 20 { 21 DataPush.push(a); 22 } 23 int Front() 24 { 25 if (DataPop.empty()) 26 { 27 while (!DataPush.empty()) 28 { 29 DataPop.push(DataPush.top()); 30 DataPush.pop(); 31 } 32 } 33 return DataPop.top(); 34 } 35 36 void Pop() 37 { 38 if (DataPop.empty()) 39 { 40 while (!DataPush.empty()) 41 { 42 DataPop.push(DataPush.top()); 43 DataPush.pop(); 44 } 45 } 46 DataPop.pop(); 47 } 48 }; 49 50 51 void Test() 52 { 53 54 StackToQueue myQueue; 55 myQueue.Push(1); 56 myQueue.Push(2); 57 myQueue.Push(3); 58 myQueue.Push(4); 59 myQueue.Push(5); 60 myQueue.Push(6); 61 62 cout << myQueue.Front() << endl; 63 myQueue.Pop(); 64 cout << myQueue.Front() << endl; 65 myQueue.Pop(); 66 cout << myQueue.Front() << endl; 67 68 myQueue.Push(7); 69 myQueue.Push(8); 70 71 cout << myQueue.Front() << endl; 72 }