Question #200740

  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.


(Note: I need easiest solution of this program urgently)



Expert's answer

#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;
}    
LATEST TUTORIALS
APPROVED BY CLIENTS