C++ stack template implementation using linked list
By Abdullah Jamal
C++ stack implementation using linked list to support custom datatypes. Includes unit testing.
C++ stack template implementation using linked list
C++ STL stack implementation using linked list to support custom datatypes. Supports throwing errors for underflows.
Stack template is in a separate header file, stack.h.
To use the custom stack template, import the header file using #include "stack.h"
Includes unit testing.
Requirements : C++ 11
To Compile and run the application
g++ stack.tests.cpp
./a.out
template
class Stack
{
private:
class Node
{
public:
T data;
Node *next;
Node()
{
data = nullptr;
next = nullptr;
}
Node(T value)
{
data = value;
next = nullptr;
}
};
Node *head;
int stackSize;
public:
Stack()
{
this->head = nullptr;
this->stackSize = 0;
}
~Stack()
{
// delete the dynamic memory to avoid memory leak
}
void push(T value)
{
Node *temp = new Node(value);
temp->next = head;
this->head = temp;
this->stackSize += 1;
}
void pop()
{
if (this->stackSize == 0)
{
throw underflow_error("stack is empty");
}
Node *temp = this->head;
this->head = this->head->next;
temp->next = nullptr;
delete temp;
this->stackSize--;
}
bool isEmpty()
{
return this->stackSize == 0 ? true : false;
}
T top()
{
if (this->stackSize == 0)
{
throw underflow_error("stack is empty");
}
return this->head->data;
}
int size()
{
return this->stackSize;
}
};
Comments