Implement stack data structure and its operations using arrays.

Implement stack data structure and its operations using arrays.




 #include <iostream>

using namespace std;


const int MAX_SIZE = 100;


class Stack {

private:

    int top;            // Index of the top element in the stack

    int arr[MAX_SIZE];  // Array to store the stack elements


public:

    Stack() {

        top = -1;       // Initialize top to -1 to indicate an empty stack

    }


    bool isEmpty() {

        return (top == -1);

    }


    bool isFull() {

        return (top == MAX_SIZE - 1);

    }


    void push(int value) {

        if (isFull()) {

            cout << "Stack Overflow: Cannot push element " << value << ". Stack is full." << endl;

            return;

        }


        top++;

        arr[top] = value;

        cout << "Pushed element: " << value << endl;

    }


    void pop() {

        if (isEmpty()) {

            cout << "Stack Underflow: Cannot pop element. Stack is empty." << endl;

            return;

        }


        int poppedElement = arr[top];

        top--;

        cout << "Popped element: " << poppedElement << endl;

    }


    int peek() {

        if (isEmpty()) {

            cout << "Stack is empty." << endl;

            return -1;

        }


        return arr[top];

    }


    void display() {

        if (isEmpty()) {

            cout << "Stack is empty." << endl;

            return;

        }


        cout << "Stack elements: ";

        for (int i = 0; i <= top; i++) {

            cout << arr[i] << " ";

        }

        cout << endl;

    }

};


int main() {

    Stack stack;


    stack.push(1);

    stack.push(2);

    stack.push(3);

    stack.display();


    cout << "Top element: " << stack.peek() << endl;


    stack.pop();

    stack.display();


    stack.pop();

    stack.pop();


    stack.display();


    return 0;

}


Comments

Popular posts from this blog

Differentiate between Unimodal, Bimodal and Multimodal with graphic representation.

Using Titanic dataset, do the following: a. Find total number of passengers with age less than 30 b. Find total fare paid by passengers of first class c. Compare number of survivors of each passenger class

Import iris data using sklearn library . Compute mean, mode, median, standard deviation, confidence interval and standard error for each feature ii. Compute correlation coefficients between each pair of features and plot heatmap iii. Find covariance between length of sepal and petal iv. Build contingency table for class feature