Answer to Question #198579 in C++ for MUNEEB

Question #198579
  1. Take integer input from user and store it in the form of 1) stacks 2) queues and 3) Linked list.
  2. Sort the data stored in 1) stack 2) queue and 3) linked list entered in part 1
  3. Take user input and insert the data at the respective position in the sorted 1) stack 2) queue and 3) linked list.
1
Expert's answer
2021-05-27T06:25:52-0400
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>

using namespace std;

stack<int> sorted_stack(stack<int> a) {
    int tmp[a.size()];
    int i = 0;
    while (!a.empty()) {
        tmp[i++] = a.top();
        a.pop();
    }
    sort(tmp, tmp + i);
    int j = 0;
    while (j < i) {
        a.push(tmp[j++]);
    }
    return a;
}

void print_stack(stack<int> a) {
    int tmp[a.size()];
    int i = 0;
    while (!a.empty()) {
        tmp[i++] = a.top();
        a.pop();
    }
    while (i > 0) {
        cout << tmp[--i] << " ";
    }
    cout << "\n";
}

queue<int> sorted_queue(queue<int> b) {
    int tmp[b.size()];
    int i = 0;
    while (!b.empty()) {
        tmp[i++] = b.front();
        b.pop();
    }
    sort(tmp, tmp + i);
    int j = 0;
    while (j < i) {
        b.push(tmp[j++]);
    }
    return b;
    
}

void print_queue(queue<int> b) {
    int i = 0;
    while (!b.empty()) {
        cout << b.front() << " ";
        b.pop();
    }
    cout << "\n";
}

list<int> sorted_list(list<int> c) {
    c.sort();
    return c;
}

void print_list(list<int> c) {
    for (int i : c) {
        cout << i << " ";
    }
    cout << "\n";
}

int main() 
{
    int n;
    int x;
    
    // 1
    stack<int> a;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> x;
        a.push(x);
    }
    cout << "before sorting: ";
    print_stack(a);
    a = sorted_stack(a);
    cout << "after sorting: ";
    print_stack(a);
    
    // 2
    queue<int> b;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> x;
        b.push(x);
    }
    cout << "before sorting: ";
    print_queue(b);
    b = sorted_queue(b);
    cout << "after sorting: ";
    print_queue(b);
    
    // 3
    list<int> c;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> x;
        c.push_back(x);
    }
    cout << "before sorting: ";
    print_list(c);
    c = sorted_list(c);
    cout << "after sorting: ";
    print_list(c);
    
    return 0;
}    

example:

// stack
3
9899 74 3
before sorting: 9899 74 3 
after sorting: 3 74 9899 
// queue
4
1 2 4 3
before sorting: 1 2 4 3 
after sorting: 1 2 3 4 
// list
5
9 736 84 2 4
before sorting: 9 736 84 2 4 
after sorting: 2 4 9 84 736 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog