Sort the data stored in 1) stack 2) queue and 3) linked list . Attach the code and output.
#include <iostream>
#include <stack>
#include <queue>
#include <list>
#include <random>
#include <ctime>
using namespace std;
void SortStack(stack<int>& Stack);
void SortQueue(queue<int>& Queue);
void SortList(list<int>& List);
void Sort(int* a, int size);
int main()
{
stack<int> Stack;
queue<int> Queue;
list<int> List;
srand(time(0));
cout << "Values which will be inserted to sets: ";
for (int i = 0; i < 10; i++)
{
int temp = rand() % 50;
Stack.push(temp);
Queue.push(temp);
List.push_back(temp);
cout << temp << " ";
}
cout << endl;
SortList(List);
SortQueue(Queue);
SortStack(Stack);
cout << "Sorted values in list: ";
for (int i = 0; i < 10; i++)
{
cout << List.front() << " ";
List.pop_front();
}
cout << endl;
cout << "Sorted values in stack: ";
for (int i = 0; i < 10; i++)
{
cout << Stack.top() << " ";
Stack.pop();
}
cout << endl;
cout << "Sorted values in queue: ";
for (int i = 0; i < 10; i++)
{
cout << Queue.front() << " ";
Queue.pop();
}
cout << endl;
system("pause");
return 0;
}
void SortStack(stack<int>& Stack)
{
int* a = new int[Stack.size()];
int size = Stack.size();
for(int i = 0; i < size; i++)
{
a[i] = Stack.top();
Stack.pop();
}
Sort(a, size);
for (int i = size - 1; i >= 0; i--)
{
Stack.push(a[i]);
}
delete[]a;
}
void SortQueue(queue<int>& Queue)
{
int* a = new int[Queue.size()];
int size = Queue.size();
for (int i = 0; i < size; i++)
{
a[i] = Queue.front();
Queue.pop();
}
Sort(a, size);
for (int i = 0; i < size; i++)
{
Queue.push(a[i]);
}
delete[]a;
}
void SortList(list<int>& List)
{
int* a = new int[List.size()];
int size = List.size();
for (int i = 0; i < size; i++)
{
a[i] = List.front();
List.pop_front();
}
Sort(a, size);
for (int i = 0; i < size; i++)
{
List.push_back(a[i]);
}
delete[]a;
}
void Sort(int* a, int size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size - 1; j++)
{
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
Comments
Leave a comment