fork(2) download
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. void StackSort(int nTop, stack<int>& S);
  6.  
  7. void StackSortUtil(stack<int>& S)
  8. {
  9. for(int i=0;i<S.size(); ++i)
  10. {
  11. int nTop = S.top();
  12. S.pop();
  13. StackSort(nTop, S);
  14. }
  15. }
  16.  
  17. void StackSort(int nTop, stack<int>& S)
  18. {
  19. if(S.size() == 0)
  20. {
  21. S.push(nTop);
  22. return;
  23. }
  24.  
  25. int nT = S.top();
  26.  
  27. if(nT > nTop)
  28. {
  29. //swap
  30. int i = nTop;
  31. nTop = nT;
  32. nT = i;
  33. }
  34.  
  35. S.pop();
  36. StackSort(nT,S);
  37.  
  38. S.push(nTop);
  39. }
  40. int printStack(stack <int>& S){
  41. while( ! S.empty()) {
  42. cout<< S.top() <<"\n";
  43. S.pop();
  44. }
  45. }
  46. int main()
  47. {
  48. std::stack<int> Stk;
  49. Stk.push(10);
  50. Stk.push(13);
  51. Stk.push(41);
  52. Stk.push(72);
  53. Stk.push(15);
  54.  
  55. StackSortUtil(Stk);
  56. cout << "==Stack in decending order==\n";
  57. printStack(Stk);
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
==Stack in decending order==
72
41
15
13
10