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