|
| 1 | +/** |
| 2 | + * @file |
| 3 | + * @author danghai |
| 4 | + * @author [Piotr Idzik](https://github.com/vil02) |
| 5 | + * @brief This class specifies the basic operation on a stack as a linked list |
| 6 | + **/ |
| 7 | +#ifndef DATA_STRUCTURES_STACK_HPP_ |
| 8 | +#define DATA_STRUCTURES_STACK_HPP_ |
| 9 | + |
| 10 | +#include <stdexcept> /// for std::invalid_argument |
| 11 | + |
| 12 | +#include "node.hpp" /// for Node |
| 13 | + |
| 14 | +/** Definition of the stack class |
| 15 | + * \tparam value_type type of data nodes of the linked list in the stack should |
| 16 | + * contain |
| 17 | + */ |
| 18 | +template <class ValueType> |
| 19 | +class stack { |
| 20 | + public: |
| 21 | + using value_type = ValueType; |
| 22 | + |
| 23 | + /** Show stack */ |
| 24 | + void display() const { |
| 25 | + std::cout << "Top --> "; |
| 26 | + display_all(this->stackTop.get()); |
| 27 | + std::cout << '\n'; |
| 28 | + std::cout << "Size of stack: " << size << std::endl; |
| 29 | + } |
| 30 | + |
| 31 | + std::vector<value_type> toVector() const { |
| 32 | + return push_all_to_vector(this->stackTop.get(), this->size); |
| 33 | + } |
| 34 | + |
| 35 | + private: |
| 36 | + void ensureNotEmpty() const { |
| 37 | + if (isEmptyStack()) { |
| 38 | + throw std::invalid_argument("Stack is empty."); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public: |
| 43 | + /** Determine whether the stack is empty */ |
| 44 | + bool isEmptyStack() const { return (stackTop == nullptr); } |
| 45 | + |
| 46 | + /** Add new item to the stack */ |
| 47 | + void push(const value_type& item) { |
| 48 | + auto newNode = std::make_shared<Node<value_type>>(); |
| 49 | + newNode->data = item; |
| 50 | + newNode->next = stackTop; |
| 51 | + stackTop = newNode; |
| 52 | + size++; |
| 53 | + } |
| 54 | + |
| 55 | + /** Return the top element of the stack */ |
| 56 | + value_type top() const { |
| 57 | + ensureNotEmpty(); |
| 58 | + return stackTop->data; |
| 59 | + } |
| 60 | + |
| 61 | + /** Remove the top element of the stack */ |
| 62 | + void pop() { |
| 63 | + ensureNotEmpty(); |
| 64 | + stackTop = stackTop->next; |
| 65 | + size--; |
| 66 | + } |
| 67 | + |
| 68 | + /** Clear stack */ |
| 69 | + void clear() { |
| 70 | + stackTop = nullptr; |
| 71 | + size = 0; |
| 72 | + } |
| 73 | + |
| 74 | + private: |
| 75 | + std::shared_ptr<Node<value_type>> stackTop = |
| 76 | + {}; /**< Pointer to the stack */ |
| 77 | + std::size_t size = 0; ///< size of stack |
| 78 | +}; |
| 79 | + |
| 80 | +#endif // DATA_STRUCTURES_STACK_HPP_ |
0 commit comments