Ideas:
Team:
Only stack S1 as the queue.
Out team:
The Stack S2 as the team, if the stack S1 is not empty, S2 is empty, the team will s1 the element into the S2, then pop ();
Otherwise, the S2 is not empty, the team directly in the Stack S2 pop ();
#include <iostream> #include <stack> #include <assert.h>using namespace Std;template<class t> Classqueue{public:queue (): _size (0) {}void appendtail (T num) {s1.push (num); _size++;} void Deletehead () {assert (_size>0), if (S2.empty ()) {while (S1.size ()!=1) {S2.push (S1.top ()); S1.pop ();} S1.pop ();} Else{s2.pop ();} _size--;} t& Top () {assert (_size>0), if (S2.empty ()) {while (S1.size ()!=1) {S2.push (S1.top ());} return S1.top ();} Else{return s2.top ();}} private:stack<t> s1;stack<t> s2;int _size;}; int main () {queue<int> q;q.appendtail (1); Q.appendtail (2); Q.appendtail (3); Q.appendtail (4); Q.deletehead (); Q.deletehead (); Q.deletehead (); Q.deletehead (); Q.appendtail (5); Cout<<q.top () <<endl;system ("pause"); return 0;}
This article from "Liveyoung" blog, reproduced please contact the author!
Two stacks to implement a team.