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.
Multi Line Text.
#include <stack>
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
stack<int> S1;
for (int i = 0; i < 15; i++)
{
S1.push(i * 2);
}
int P = round(S1.size() / 2.0);
stack<int> temp;
int insertValue = 5000;
for (int i = S1.size(); i > P; i--)
{
temp.push(S1.top());
S1.pop();
}
S1.push(insertValue);
int numberOfValues = temp.size();
for (int i = 0; i < numberOfValues; i++)
{
S1.push(temp.top());
temp.pop();
}
cout << "Stack: ";
numberOfValues = S1.size();
for (int i = 0; i < numberOfValues; i++)
{
cout << S1.top() << " ";
S1.pop();
}
cout << endl;
system("pause");
return 0;
}
Comments
Leave a comment