Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- using namespace std;
- bool isInteger(string s);
- int toInteger(string s);
- void inputStack(stack<int>& s);
- void outputStack(stack<int> s);
- void sortedInsert(stack<int>& st, int element);
- void sortStack(stack<int>& st);
- int main()
- {
- stack<int> st;
- cout << "Enter stack elements: ";
- inputStack(st);
- sortStack(st);
- cout << "Sorted stack: ";
- outputStack(st);
- cout << endl;
- return 0;
- }
- bool isInteger(string s)
- {
- bool state = true;
- for (int i = 0; state && i < s.length(); i++)
- {
- if (i == 0 && s[i] == '-' && s.length() > 1)
- {
- continue;
- }
- if (!isdigit(s[i]))
- {
- state = false;
- }
- }
- return state;
- }
- int toInteger(string s)
- {
- int num = 0;
- for (int i = 0; i < s.length(); i++)
- {
- if (i == 0 && s[i] == '-')
- {
- continue;
- }
- num = 10 * num + (s[i] - '0');
- }
- return (s[0] == '-') ? -num : num;
- }
- void inputStack(stack<int>& s)
- {
- string input;
- while(1)
- {
- cin >> input;
- if (isInteger(input))
- {
- s.push(toInteger(input));
- }
- else
- {
- return;
- }
- }
- }
- void outputStack(stack<int> s)
- {
- while (!s.empty())
- {
- cout << s.top() << " ";
- s.pop();
- }
- }
- void sortedInsert(stack<int>& st, int element)
- {
- if (st.empty() || element > st.top())
- {
- st.push(element);
- }
- else
- {
- int temp = st.top();
- st.pop();
- sortedInsert(st, element);
- st.push(temp);
- }
- }
- void sortStack(stack<int>& st)
- {
- if (!st.empty())
- {
- int temp = st.top();
- st.pop();
- sortStack(st);
- sortedInsert(st, temp);
- }
- }
Add Comment
Please, Sign In to add comment