forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.cpp
84 lines (72 loc) · 2.12 KB
/
stack.cpp
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
#include<iostream>
#include<cassert>
#include<memory>
namespace my {
/**
* implementation using linked list
* [value][next] -> [value][next] -> ... -> [value][next]
* (top Node) (intermediat Nodes)
* left most Node represents top element of stack
*/
template<typename T>
struct Node {
/**
* next: will store right Node address
*/
T value;
std::unique_ptr<Node<T>> next;
Node(const T& V) : value(V) { }
};
template<typename T>
class stack {
private:
/**
* top_pointer: points to left most node
* count: keeps track of current number of elements present in stack
*/
std::unique_ptr<Node<T>> top_pointer;
size_t count;
public:
stack() : count(0ULL) { }
void push(const T& element) {
auto new_node = std::make_unique<Node<T>>(element);
new_node->next = std::move(top_pointer);
top_pointer = std::move(new_node);
count = count + 1;
}
void pop() {
if (count > 0) {
top_pointer = std::move(top_pointer->next);
count = count - 1;
}
}
T& top() {
assert(count > 0 and "calling top() on an empty stack");
return top_pointer->value;
}
// returning mutable reference can very be usefull if someone wants to modify top element
T const& top() const {
assert(count > 0 and "calling top() on an empty stack");
return top_pointer->value;
}
size_t size() const { return count; }
bool empty() const { return count == 0; }
~stack() {
while (top_pointer.get() != nullptr) {
top_pointer = std::move(top_pointer->next);
}
}
};
}
int main() {
my::stack<int> intStack;
intStack.push(4);
intStack.push(5);
intStack.push(9);
int topElement = intStack.top();
intStack.pop();
std::cout << topElement << '\n';
std::cout << intStack.size() << '\n';
std::cout << intStack.top() << '\n';
return 0;
}