vencinachev

Zad1

May 28th, 2021 (edited)
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <iostream>
  2. #include <stack>
  3.  
  4. using namespace std;
  5.  
  6. bool isInteger(string s);
  7. int toInteger(string s);
  8. void inputStack(stack<int>& s);
  9. void outputStack(stack<int> s);
  10. void sortedInsert(stack<int>& st, int element);
  11. void sortStack(stack<int>& st);
  12.  
  13. int main()
  14. {
  15.     stack<int> st;
  16.     cout << "Enter stack elements: ";
  17.     inputStack(st);
  18.     sortStack(st);
  19.     cout << "Sorted stack: ";
  20.     outputStack(st);
  21.     cout << endl;
  22.     return 0;
  23. }
  24.  
  25. bool isInteger(string s)
  26. {
  27.     bool state = true;
  28.     for (int i = 0; state && i < s.length(); i++)
  29.     {
  30.         if (i == 0 && s[i] == '-' &&  s.length() > 1)
  31.         {
  32.             continue;
  33.         }
  34.         if (!isdigit(s[i]))
  35.         {
  36.             state = false;
  37.         }
  38.     }
  39.  
  40.     return state;
  41. }
  42.  
  43. int toInteger(string s)
  44. {
  45.     int num = 0;
  46.     for (int i = 0; i < s.length(); i++)
  47.     {
  48.         if (i == 0 && s[i] == '-')
  49.         {
  50.             continue;
  51.         }
  52.         num = 10 * num + (s[i] - '0');
  53.     }
  54.     return (s[0] == '-') ? -num : num;
  55. }
  56.  
  57. void inputStack(stack<int>& s)
  58. {
  59.     string input;
  60.     while(1)
  61.     {
  62.         cin >> input;
  63.  
  64.         if (isInteger(input))
  65.         {
  66.             s.push(toInteger(input));
  67.         }
  68.         else
  69.         {
  70.             return;
  71.         }
  72.     }
  73. }
  74.  
  75. void outputStack(stack<int> s)
  76. {
  77.     while (!s.empty())
  78.         {
  79.         cout << s.top() << " ";
  80.         s.pop();
  81.     }
  82. }
  83.  
  84. void sortedInsert(stack<int>& st, int element)
  85. {
  86.     if (st.empty() || element > st.top())
  87.     {
  88.         st.push(element);
  89.     }
  90.     else
  91.     {
  92.         int temp = st.top();
  93.         st.pop();
  94.         sortedInsert(st, element);
  95.         st.push(temp);
  96.     }
  97. }
  98.  
  99. void sortStack(stack<int>& st)
  100. {
  101.     if (!st.empty())
  102.     {
  103.         int temp = st.top();
  104.         st.pop();
  105.         sortStack(st);
  106.         sortedInsert(st, temp);
  107.     }
  108. }
  109.  
  110.  
Add Comment
Please, Sign In to add comment