Followers

Wednesday, July 17, 2024

An implementation of stack operations using an array in C++.


 

    # include <iostream>

    using namespace std;

    class Stack {

        private:

        int top;

        int maxSize;

        int* stackArray;

        public:

        Stack(int size) {

        maxSize = size;

        stackArray = new int[maxSize];

        top = -1;

        }

        ~Stack() {

        delete[] stackArray;

        }

        void push(int value) {

            if (isFull()) {

                cout << "Stack overflow! Cannot push " << value << endl;

            } else {

                stackArray[++top] = value;

            }

        }

    int pop() {

        if (isEmpty()) {

            cout << "Stack underflow! Cannot pop" << endl;

            return -1; // Assuming -1 as error value for stack underflow

        } else {

            return stackArray[top--];

        }

    }

    int peek() {

        if (isEmpty()) {

            cout << "Stack is empty! Cannot peek" << endl;

            return -1; // Assuming -1 as error value for empty stack

            } else {

            return stackArray[top];

            }

        }

        bool isEmpty() {

            return top == -1;

        }

        bool isFull() {

        return top == maxSize - 1;

        }

    };


    int main() {

        int size;

        cout << "Enter the size of the stack: ";

        cin >> size;

        Stack stack(size);

        stack.push(10);

        stack.push(20);

        stack.push(30);

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

        cout << "Elements popped from stack: " << stack.pop() << ", " << stack.pop() << ", " <<  stack.pop() << endl;

    // Attempt to pop from empty stack

        stack.pop();

        return 0;

    }


  • 1. Stack Class:

    • Contains a constructor to initialise the stack with a given size.
    • Contains a destructor to deallocate the memory used by the stack.
    • Implements push to add an element to the stack.
    • Implements pop to remove and return the top element from the stack.
    • Implements peek to return the top element without removing it.
    • Implements isEmpty to check if the stack is empty.
    • Implements isFull to check if the stack is full.
  • 2. Main Function:

    • Takes the size of the stack from the user.
    • Demonstrates basic stack operations (push, pop, peek).
  • No comments:

    Post a Comment