Created
October 12, 2023 00:41
-
-
Save cjnghn/d3a8ff94c244bc7682011ef267787e5d to your computer and use it in GitHub Desktop.
stack implementation
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
#ifndef CUSTOMERROR_H_ | |
#define CUSTOMERROR_H_ | |
#include <string> | |
#include <iostream> | |
class RuntimeException { | |
public: | |
RuntimeException(const std::string& err) : error_message_(err) {} | |
std::string GetMessage() const { | |
return error_message_; | |
} | |
private: | |
std::string error_message_; | |
}; | |
inline std::ostream& operator<<(std::ostream& out, const RuntimeException& e) { | |
return out << e.GetMessage(); | |
} | |
#endif // CUSTOMERROR_H_ | |
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
#ifndef STACK_H_ | |
#define STACK_H_ | |
#include "customerror.h" | |
template<typename T> | |
class Node { | |
public: | |
T value; | |
Node<T>* next; | |
Node() : next(nullptr) {} | |
Node(T val, Node<T>* next_node) : value(val), next(next_node) {} | |
}; | |
class StackUnderflowException : public RuntimeException { | |
public: | |
StackUnderflowException(const std::string& err) | |
: RuntimeException(err) {} | |
}; | |
template<typename T> | |
class Stack { | |
public: | |
Stack() : size_(0), top_(nullptr) {} | |
~Stack() { | |
Node<T>* current = top_; | |
while (current != nullptr) { | |
Node<T>* next_node = current->next; | |
delete current; | |
current = next_node; | |
} | |
} | |
void Push(T val) { | |
top_ = new Node<T>(val, top_); | |
size_++; | |
} | |
T Top() { | |
if (size_ == 0) { | |
throw StackUnderflowException("Can't top. stack is empty"); | |
} | |
return top_->value; | |
} | |
void Pop() { | |
if (size_ == 0) { | |
throw StackUnderflowException("Can't pop. stack is empty"); | |
} | |
Node<T>* next_node = top_->next; | |
delete top_; | |
top_ = next_node; | |
size_--; | |
} | |
private: | |
int size_; | |
Node<T>* top_; | |
}; | |
#endif // STACK_H_ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment