Answer to Question #198486 in C++ for Ayesha

Question #198486

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. please send me answer of this question . thank you.



1
Expert's answer
2021-05-26T06:53:11-0400
#include <iostream>
#include <cmath>

using namespace std;

class Stack {
    private:
    int size = 0;
    int elem[100000];
    public:
    bool insert(int item) {
        int sz = this->size;
        if (sz + 1 < 100000) {
            int idx = round(sz / 2);
            for (int i = sz; i > idx; i--) {
                this->elem[i] = this->elem[i-1];
            }
            this->elem[idx] = item;
            this->size++;
            return true;
        } else {
            return false;
        }
    }
    void display() {
        for (int i = 0; i < size;i++)
            cout << this->elem[i] << " ";
        cout << endl;
    }
};

int main()
{
    Stack *s = new Stack();
    
    s->insert(1);
    s->display();
    
    s->insert(2);
    s->display();
    
    s->insert(3);
    s->display();
    
    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