Created
September 22, 2023 16:24
-
-
Save axyiee/a437d0c0d9f5d83a249bff961d608e73 to your computer and use it in GitHub Desktop.
A generic Stack data structure based upon linked lists.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory> | |
using namespace std; | |
template <typename T> | |
class LinkedStack | |
{ | |
class Node | |
{ | |
public: | |
Node(T value) : data(value), next(nullptr) {} | |
T data; | |
shared_ptr<Node> next; | |
}; | |
shared_ptr<Node> top; | |
public: | |
LinkedStack() : top(nullptr) {} | |
~LinkedStack(); | |
void push(T data); | |
void pop(); | |
T *peek(); | |
int length(); | |
template <typename... Args> | |
void push(Args... data) | |
{ | |
(push(data), ...); | |
} | |
}; | |
template <typename T> | |
LinkedStack<T>::~LinkedStack() | |
{ | |
while (length() != 0) | |
{ | |
pop(); | |
} | |
} | |
template <typename T> | |
int LinkedStack<T>::length() | |
{ | |
int size = 0; | |
shared_ptr<Node> current = top; | |
while (current) | |
{ | |
size++; | |
current = current->next; | |
} | |
return size; | |
} | |
template <typename T> | |
void LinkedStack<T>::push(T data) | |
{ | |
shared_ptr<Node> node(new Node(data)); | |
node->next = top; | |
top = node; | |
} | |
template <typename T> | |
void LinkedStack<T>::pop() | |
{ | |
if (length() == 0) | |
{ | |
return; | |
} | |
shared_ptr<Node> temp = top; | |
top = temp->next; | |
} | |
template <typename T> | |
T *LinkedStack<T>::peek() | |
{ | |
if (length() == 0) | |
{ | |
return nullptr; | |
} | |
return &(top->data); | |
} | |
int main() | |
{ | |
LinkedStack<int> *stack = new LinkedStack<int>(); | |
stack->push(16, 32, 64); | |
std::cout << "Added 3 elements to stack" << std::endl; | |
std::cout << "Stack Length: " << stack->length() << std::endl; | |
std::cout << "Top Element: " << *stack->peek() << std::endl; | |
stack->pop(); | |
stack->pop(); | |
std::cout << "Stack Length after Pops: " << stack->length() << std::endl; | |
stack->pop(); | |
if (stack->peek() == nullptr) | |
{ | |
std::cout << "Stack is empty." << std::endl; | |
} | |
delete stack; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment