Stacks in C++

Mannan Ul Haq
0

What is Stack?

A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Think of it as a pile of plates; you can only take the top plate off the pile, and you can only add a new plate on the top.

Operations:

1. Push: Adds an element to the top of the stack.

2. Pop: Removes the top element from the stack.

3. Top: Returns the top element without removing it.

4. IsEmpty: Checks if the stack is empty.

5. IsFull: Checks if the stack is full (only relevant for array-based implementations).


Array-Based Stack:

An array-based stack uses an array to store stack elements. This approach involves managing a fixed-size array and a variable to keep track of the top element's position.


Example:

Here is a simple implementation of a stack using an array in C++:


#include <iostream>
using namespace std;

template <class T>
class Stack {
private:
    T* Array;
    int Max_Size;
    int Current_Size;
    int Current_TopIndex;

public:
    // Constructor to initialize the stack
    Stack(int Size = 10) {
        this->Max_Size = Size;
        this->Array = new T[this->Max_Size];
        this->Current_Size = 0;
        this->Current_TopIndex = -1;
    }

    // Destructor to clean up allocated memory
    ~Stack() {
        delete[] Array;
    }

    // Check if the stack is empty
    bool IsEmpty() {
        return Current_Size == 0;
    }

    // Check if the stack is full
    bool IsFull() {
        return Current_Size == Max_Size;
    }

    // Push operation to add an element to the stack
    bool Push(T value) {
        if (IsFull()) {
            cout << "Stack is full!" << endl;
            return false;
        } else {
            Current_TopIndex++;
            Array[Current_TopIndex] = value;
            Current_Size++;
            return true;
        }
    }

    // Pop operation to remove the top element from the stack
    bool Pop() {
        if (IsEmpty()) {
            cout << "Stack is empty!" << endl;
            return false;
        } else {
            Current_TopIndex--;
            Current_Size--;
            return true;
        }
    }

    // Peek operation to return the top element without removing it
    T Top() {
        if (IsEmpty()) {
            cout << "Stack is empty!" << endl;
            throw out_of_range("Stack is empty");
        } else {
            return Array[Current_TopIndex];
        }
    }

};

int main() {
    Stack<int> stack(5);

    stack.Push(1);
    stack.Push(2);
    stack.Push(3);

    stack.Pop();

    cout << "Top element: " << stack.Top() << endl;  // Output: Top element: 2

    return 0;
}
Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !