-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListStack.hpp
More file actions
94 lines (80 loc) · 1.7 KB
/
Copy pathListStack.hpp
File metadata and controls
94 lines (80 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#pragma once
#include "IStack.hpp"
#include <cstddef> // std::size_t
#include <forward_list>
#include <stdexcept> // std::runtime_error
namespace wndx::algo {
namespace ds {
template<typename T>
class ListStack : public IStack<T>
{
protected:
std::size_t m_size {0};
std::forward_list<T> stack {};
public:
// create an empty stack
ListStack()
{}
// create a stack with an initial element
ListStack(const T &elem)
{
push(elem);
}
virtual ~ListStack() = default;
/**
* Empty this stack, O(n)
*/
void clear()
{
stack.clear();
}
/**
* return the size of the stack, O(1)
*/
virtual std::size_t size() const
{
return m_size;
}
/**
* check that stack is empty, O(1)
*/
virtual constexpr bool empty() const
{
return stack.empty();
}
/**
* add elem at the top of the stack, O(1)
*/
virtual void push(const T &elem)
{
stack.push_front(elem);
++m_size;
}
/**
* return & remove elem at the top of the stack, O(1).
* throws error if the stack is empty.
*/
virtual T pop()
{
if (empty()) {
throw std::runtime_error("Empty Stack");
}
T data { stack.front() }; // tmp store the data
stack.pop_front();
--m_size;
return data;
}
/**
* return elem at the top of the stack, O(1).
* throws error if the stack is empty.
*/
virtual T peek() const
{
if (empty()) {
throw std::runtime_error("Empty Stack");
}
return stack.front();
}
};
} // namespace ds
} // namespace wndx::algo