Stacks Explained: A Comprehensive Guide

Data Structures 2024-09-24 C++ 6 min read

This is the constructor for the Stack class. It initializes an empty stack with a size of 0 and sets the head to nullptr.

template <typename T>
Stack<T>::Stack(/* args */)
{
    this->size = 0;
    this->head = nullptr;
}

This is the destructor for the Stack class. It ensures that all allocated memory is freed when the stack is no longer needed by popping all the elements from the stack.

template <typename T>
Stack<T>::~Stack()
{
    while (!this->isEmpty())
        T item = this->pop();
}

The push function adds a new element to the top of the stack. It creates a new node and links it as the new head of the stack.

template <typename T>
void Stack<T>::push(T value)
{
    Node<T> *new_head = new Node<T>(value);
    new_head->prev = this->head;
    this->head = new_head;
    this->size++;
}

The pop function removes the top element from the stack. If the stack is empty, it throws an error. Otherwise, it returns the top value and adjusts the head to point to the previous element.

template <typename T>
T Stack<T>::pop()
{
    if (this->isEmpty()) throw std::out_of_range("Stack is empty");
    T value = this->head->value;
    Node<T> *old_head = this->head;
    this->head = old_head->prev;
    delete old_head;
    this->size--;
    return value;
}

The isEmpty function checks whether the stack is empty by verifying if the head is nullptr.

template <typename T>
bool Stack<T>::isEmpty()
{
    return this->head == nullptr;
}

This is a sample main function that demonstrates how to use the Stack class by pushing elements onto the stack and then popping them off.

#include <iostream>
#include <string>
#include <vector>
#include 'Stack.h'

using namespace std;

int main()
{
    Stack<string> stack = Stack<string>();
    vector<string> sampleVec = {"This","is","a","sample","vector"};
    cout << stack.isEmpty() << endl;
    for (int i = 0; i < sampleVec.size(); i++)
{
        cout << "Push: " << sampleVec[i] << endl;
        stack.push(sampleVec[i]);
}

Comments

Be the first one to comment!