Both of these operations are recursive implementations, Hanoi thought.
#include <iostream>#include <stack>using namespace STD;voidReverse Stack<int>&s)//Reverse Stack{if(s.size () = =0)return;intA=s.top (); S.pop ();if(s.size () = =0) {S.push (a);return; } reverse (s);intB=s.top (); S.pop (); Reverse (s); S.push (a); Reverse (s); S.push (b);}voidSort ( Stack<int>&s)//stack top magnification element{if(s.size () = =0)return;intA=s.top (); S.pop ();if(s.size () = =0) {S.push (a);return; } Sort (s);intB=s.top (); S.pop ();if(A<B) {S.push (a); Sort (s); S.push (b); }Else{S.push (b); Sort (s); S.push (a); }}intMain () { Stack<int>S for(intI=0;i<Ten; ++i) S.push (i); Reverse (s); Sort (s); while(!s.empty ()) {cout<<s.top () <<endl; S.pop (); } getchar ();return 0;}
The results of the operation are as follows:
O (1) Reverse stack and sort stack of spatial complexity