From 46f8a4c043b992f3f43d2d3305f5558469f6ebfa Mon Sep 17 00:00:00 2001 From: Kevin Date: Tue, 18 Jun 2024 01:14:29 -0700 Subject: [PATCH] Implemented stack class --- Stack.cpp | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++ StackNode.h | 3 +++ 2 files changed, 59 insertions(+) create mode 100644 Stack.cpp diff --git a/Stack.cpp b/Stack.cpp new file mode 100644 index 0000000..d33c862 --- /dev/null +++ b/Stack.cpp @@ -0,0 +1,56 @@ +#include "Stack.h" + +// Destructor +template +Stack::~Stack() { + while (!isEmpty()) { + pop(); + } +} + +// Push an element onto the stack +template +void Stack::push(const T &data) { + auto *newNode = new StackNode(data); + newNode->next = top; + top = newNode; + count++; +} + +// Pop the top element from the stack +template +T Stack::pop() { + if (isEmpty()) { + throw std::out_of_range("Stack is empty. Cannot pop."); + } + T data = top->data; + StackNode *temp = top; + top = top->next; + delete temp; + count--; + return data; +} + +// Get the top element of the stack without removing it +template +T Stack::peek() { + if (isEmpty()) { + throw std::out_of_range("Stack is empty. Cannot peek."); + } + return top->data; +} + +// Get the number of elements in the stack +template +int Stack::getCount() const { + return count; +} + +// Check if the stack is empty +template +bool Stack::isEmpty() const { + return count == 0; +} + +// Explicit instantiation of the template class for the desired type(s) +template class Stack; \ No newline at end of file diff --git a/StackNode.h b/StackNode.h index 4ad0b2a..7a24bf2 100644 --- a/StackNode.h +++ b/StackNode.h @@ -3,7 +3,10 @@ template class StackNode { + T data; + StackNode *next; + StackNode(const T &data) : data(data), next(nullptr) {} };