1.Create a stack of size M for storing integer data. Our task is to insert a node at position P = M/2. If P is a decimal number, then P can be rounded to the nearest integer.
Hint: A temporary stack can be used to store the data while inserting a new node. Use header file math.h and routine round(P), to round P to the nearest integer.
#include <stack>
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
stack<int> Stack;
int count = 0;
int value = 0;
while (true)
{
cout << "Enter value for insert in stack (0 - to exit): ";
cin >> value;
if (value == 0) break;
count++;
Stack.push(value);
}
int P = round(Stack.size() / 2.0);
stack<int> temp;
int Insert = 0;
cout << "Enter insert value: ";
cin >> Insert;
for (int i = Stack.size(); i > P; i--)
{
temp.push(Stack.top());
Stack.pop();
}
Stack.push(Insert);
int quantity = temp.size();
for (int i = 0; i < quantity; i++)
{
Stack.push(temp.top());
temp.pop();
}
cout << "Stack now is: ";
quantity = Stack.size();
for (int i = 0; i < quantity; i++)
{
cout << Stack.top() << " ";
Stack.pop();
}
cout << endl;
system("pause");
return 0;
}
Comments
Leave a comment