As the name implies (?) Similar to a monotonic stack? Maintain a monotonically decreasing stack. Once the element that is ready to stack is larger than the top of the stack, the stack pops up until the element that is ready to stack is less than or equal to the top of the stack, and the ejected element presses into the other TMP stack.
1#include <iostream>2#include <stack>3#include <cstdlib>4#include <ctime>5 using namespacestd;6 7 voidStacksort (stack<int>&s)8 {9stack<int>tmp;Ten while(!S.empty ()) { One Tmp.push (S.top ()); A S.pop (); - } - while(!Tmp.empty ()) { the if(S.empty ()) {S.push (Tmp.top ()); Tmp.pop ();} - Else{ - intx=tmp.top (); - Tmp.pop (); + if(x<=s.top ()) s.push (x); - Else{ + while(!s.empty () &&x>S.top ()) { A Tmp.push (S.top ()); at S.pop (); - } - s.push (x); - } - } - } in } - to voidDisplay (stack<int>s) +{ while(!s.empty ()) cout<<s.top () <<Endl,s.pop (); -cout<<Endl; the } * intMainintargcChar**argv) ${Const intn{ -};Panax NotoginsengSrand ((unsigned) time (0)); -stack<int>s; the for(inti{0};i<n;i++) S.push (rand ()% -); +cout<<"before sorting:"<<endl<<Endl; Display (s); Acout<<"After sorting:"<<Endl; Stacksort (s); Display (s); the return 0; +}
S
Tmp:8 7 9
S:9
Tmp:8 7
S:9 7
Tmp:8
S:9 8
Tmp:7
S:9 8 7
Tmp:
C++_homework_stacksort