Stack Implementation

Estimated reading: 3 minutes 126 Views

This code defines a simple stack class with basic operations like push, pop, getTop, and print. Here’s a breakdown of the code:

#include <iostream>
using namespace std;

const int MAX_SIZE = 100;

class Stack {
private:
    int top;            // Index of the top element in the stack
    int item[MAX_SIZE]; // Array to store stack elements

public:
    // Constructor: Initializes top to -1 (empty stack)
    Stack() : top(-1) {}

    // Function to push an element onto the stack
    void push(int Element) {
        if (top >= MAX_SIZE - 1) {
            cout << "Stack is full on push" << endl;
        } else {
            top++;
            item[top] = Element;
        }
    }

    // Function to check if the stack is empty
    bool isEmpty() {
        return top < 0;
    }

    // Function to pop an element from the stack
    void pop() {
        if (isEmpty()) {
            cout << "Stack is empty on pop" << endl;
        } else {
            top--;
        }
    }

    // Function to get the top element of the stack
    void getTop(int& stackTop) {
        if (isEmpty()) {
            cout << "Stack is empty on getTop" << endl;
        } else {
            stackTop = item[top];
            cout << stackTop << endl;
        }
    }

    // Function to print the elements of the stack
    void print() {
        cout << "[";
        for (int i = top; i >= 0; i--) {
            cout << item[i] << " ";
        }
        cout << "]" << endl;
    }
};

int main() {
    Stack s;

    // Push elements onto the stack
    s.push(5);
    s.push(10);
    s.push(15);
    s.push(20);

    // Print the stack
    s.print();

    // Get and print the top element of the stack
    int y = 0;
    s.getTop(y);

    // Pop an element from the stack
    s.pop();

    // Push another element onto the stack
    s.push(7);

    // Print the stack again
    s.print();

    return 0;
}

Explanation:

  • The Stack class implements a stack using an array named item. It has member functions for push, pop, getTop, isEmpty, and print.
  • In the push function, if the stack is not full, it increments the top index and adds the element to the item array at the top index.
  • The isEmpty function checks if the stack is empty by comparing the top index with -1.
  • The pop function decrements the top index if the stack is not empty.
  • The getTop function retrieves the top element of the stack and stores it in the stackTop parameter.
  • The print function prints the elements of the stack from top to bottom.
  • In the main function, a Stack object s is created and various operations like push, pop, getTop, and print are performed on it, demonstrating the usage of the stack.

 

Share this

Stack Implementation

Or copy link

CONTENTS
English