TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
stack.hpp
Go to the documentation of this file.
1
7#ifndef DATA_STRUCTURES_STACK_HPP_
8#define DATA_STRUCTURES_STACK_HPP_
9
10#include <stdexcept>
11
12#include "node.hpp"
13
18template <class ValueType>
19class stack {
20 public:
21 using value_type = ValueType;
22
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:
44 bool isEmptyStack() const { return (stackTop == nullptr); }
45
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
56 value_type top() const {
57 ensureNotEmpty();
58 return stackTop->data;
59 }
60
62 void pop() {
63 ensureNotEmpty();
64 stackTop = stackTop->next;
65 size--;
66 }
67
69 void clear() {
70 stackTop = nullptr;
71 size = 0;
72 }
73
74 private:
75 std::shared_ptr<Node<value_type>> stackTop =
76 {};
77 std::size_t size = 0;
78};
79
80#endif // DATA_STRUCTURES_STACK_HPP_
for std::invalid_argument
Definition stack.hpp:19
std::size_t size
size of stack
Definition stack.hpp:77
bool isEmptyStack() const
Definition stack.hpp:44
void pop()
Definition stack.hpp:62
void clear()
Definition stack.hpp:69
void display() const
Definition stack.hpp:24
void push(const value_type &item)
Definition stack.hpp:47
value_type top() const
Definition stack.hpp:56
std::shared_ptr< Node< value_type > > stackTop
Definition stack.hpp:75
Provides Node class and related utilities.