Answer to Question #198568 in C++ for ZAIN

Question #198568
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.

1
Expert's answer
2021-05-25T23:10:12-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog