#include <iostream>#include <stack>using namespace STD;Template<TypeNameT>classqueue{ Public: QUEUE () {} ~queue () {}voidAPPEND (ConstT val) { while(St2.empty () = =false) {//We only use ST2 to save the data, St1 as the intermediate Exchange Bridge. //First save the data in St2 in reverse order in ST1. St1.push (St2.top ()); St2.pop (); }//Then place the input value at the top of the st1. St1.push (Val); while(St1.empty () = =false) {The data in St1 is now all put in St2, //Exactly guaranteed that the new Val was at the bottom and realized the //Queue advanced after the idea. St2.push (St1.top ()); St1.pop (); } }intDelhed () {inttemp = St2.top (); St2.pop ();returnTemp }voidPrintf () { Stack<int>ST3 = St2;//print, in order to not affect the original stack, choose to use a temporary variable. while(St3.empty () = =false) {cout<<st3.top () <<" "; St3.pop (); }cout<<endl; }Private: Stack<T>ST1; Stack<T>St2;};intMain () {queue<int> QE; for(intI=0;i<Ten; i++) {QE. APPEND (i); } QE. Printf (); Sel Delhed (); Sel Printf (); Sel Delhed (); Sel Printf (); Sel Delhed (); Sel Printf (); Sel Delhed (); Sel Printf (); Sel Delhed (); Sel Printf (); Sel Delhed (); Sel Printf (); Sel Delhed (); Sel Printf ();return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Written question: Implementing a queue with two stacks