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 <iostream>
#include <cmath> // 'math.h'
using namespace std;
class Stack {
private:
int n = 0;
int elems[65536];
public:
bool insert(int item) {
if (n+1 < 65536) {
int m = round(this->n/2);
for (int i=++this->n; i > m; --i) {
this->elems[i] = this->elems[i-1];
}
this->elems[m] = item;
return true;
} else {
return false;
}
}
void print() {
for (int i = 0; i < n; i++) {
cout << this->elems[i] << " ";
}
cout << endl;
}
};
int main() {
Stack *stack = new Stack();
stack->insert(5);
stack->print(); // 5
stack->insert(6);
stack->print(); // 6 5
stack->insert(7);
stack->print(); // 6 7 5
return 0;
}
Comments
Leave a comment