Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <queue>
- using namespace std;
- bool isInteger(string s);
- int toInteger(string s);
- void inputQueue(queue<int>& q);
- void outputQueue(queue<int> q);
- // Ex.1 A
- bool isSorted(queue<int> q);
- // // Ex.1 B
- queue<int> sortedMerge(queue<int> q1, queue<int> q2);
- int main()
- {
- queue<int> a, b, c;
- cout << "Enter first queue elements: ";
- inputQueue(a);
- bool isSortedA = isSorted(a);
- cout << "Enter second queue elements: ";
- inputQueue(b);
- bool isSortedB = isSorted(b);
- cout << boolalpha << "First queue sorted: " << isSortedA << endl;
- cout << boolalpha << "Second queue sorted: " << isSortedB << endl;
- if (isSortedA && isSortedB)
- {
- cout << "Sorted merge: ";
- c = sortedMerge(a, b);
- outputQueue(c);
- }
- 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 inputQueue(queue<int>& q)
- {
- string input;
- while(1)
- {
- cin >> input;
- if (isInteger(input))
- {
- q.push(toInteger(input));
- }
- else
- {
- return;
- }
- }
- }
- void outputQueue(queue<int> q)
- {
- if (q.empty())
- {
- cout << "Queue is empty!";
- return;
- }
- while (!q.empty())
- {
- cout << q.front() << " ";
- q.pop();
- }
- }
- bool isSorted(queue<int> q)
- {
- if (q.empty())
- {
- return false;
- }
- int a = q.front();
- q.pop();
- while(!q.empty())
- {
- int b = q.front();
- q.pop();
- if (a > b)
- {
- return false;
- }
- a = b;
- }
- return true;
- }
- queue<int> sortedMerge(queue<int> q1, queue<int> q2)
- {
- queue<int> result;
- while(!q1.empty() || !q2.empty())
- {
- if (!q1.empty() && !q2.empty())
- {
- if (q1.front() < q2.front())
- {
- result.push(q1.front());
- q1.pop();
- }
- else
- {
- result.push(q2.front());
- q2.pop();
- }
- }
- else if (!q1.empty())
- {
- result.push(q1.front());
- q1.pop();
- }
- else if (!q2.empty())
- {
- result.push(q2.front());
- q2.pop();
- }
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement