fork download
  1.  
  2. #include <bits/stdc++.h>
  3. #include <iostream>
  4. using namespace std;
  5.  
  6.  
  7. void insertatsortstack(int element, stack<int> &s){
  8.  
  9. if(s.empty()==1 || element > s.top())
  10. {
  11. s.push(element);
  12. return;
  13. }
  14.  
  15. int temp=s.top();
  16. s.pop();
  17. insertatsortstack(element,s);
  18. s.push(temp);
  19. }
  20.  
  21. void sortstack(stack<int> &s){
  22. if(s.size()>0){
  23. int element=s.top();
  24. s.pop();
  25. sortstack(s);
  26. insertatsortstack(element,s);
  27. }
  28. }
  29.  
  30. int main() {
  31. // your code goes here
  32. stack<int> s;
  33. s.push(10);
  34. s.push(8);
  35. s.push(6);
  36. s.push(4);
  37. s.push(2);
  38.  
  39. while(s.size()>0)
  40. {
  41. cout<<" "<<s.top()<<" ";
  42. s.pop();
  43. }
  44. cout<< endl;
  45. s.push(10);
  46. s.push(8);
  47. s.push(6);
  48. s.push(4);
  49. s.push(2);
  50.  
  51. sortstack(s);
  52. while(s.size()>0)
  53. {
  54. cout<<" "<<s.top()<<" ";
  55. s.pop();
  56. }
  57. }
  58.  
  59.  
Success #stdin #stdout 0s 4480KB
stdin
Standard input is empty
stdout
 2  4  6  8  10 
 10  8  6  4  2