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

Load a Pandas dataframe with a selected dataset. Identify and count the missing values in a dataframe. Clean the data after removing noise as follows: a. Drop duplicate rows. b. Detect the outliers and remove the rows having outliers c. Identify the most correlated positively correlated attributes and negatively correlated attributes

The weights of 8 boys in kilograms: 45, 39, 53, 45, 43, 48, 50, 45. Find the median

Download any dataset and do the following: a. Count number of categorical and numeric features b. Remove one correlated attribute (if any) c. Display five-number summary of each attribute and show it visually