-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.h
More file actions
131 lines (100 loc) · 2.04 KB
/
Stack.h
File metadata and controls
131 lines (100 loc) · 2.04 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#pragma once
template<typename T>
class Node {
public:
T value;
Node<T>* next;
public:
Node() {
next = NULL;
}
Node(const T& _value, Node<T>* _next);
};
template<typename T>
class Stack {
private:
Node<T>* top;
size_t stackSize;
void init();
void erase();
void copyReverse(const Stack& src);
void copy(const Stack& src);
bool isEmpty();
public:
Stack();
Stack(const Stack& src);
~Stack();
Stack& operator=(const Stack& src);
size_t size();
void push(T& value);
void pop();
T& getTop();
};
template<typename T>
Node<T>::Node(const T& _value, Node<T>* _next) {
value = _value;
next = _next;
}
template <typename T> void Stack<T>::init() {
stackSize = 0;
top = NULL;
}
template<typename T> void Stack<T>::erase() {
for (size_t i = 0; i < stackSize; i++) {
this->pop();
}
}
template <typename T> void Stack<T>::copyReverse(const Stack<T>& src) {
Node<T>* node = src.top;
for (size_t i = 0; i < src.stackSize; i++) {
push(node->value);
node = node->next;
}
stackSize = src.stackSize;
}
template <typename T> void Stack<T>::copy(const Stack<T>& src) {
Stack<T> reversed;
reversed.copyReverse(src);
this->copyReverse(reversed);
}
template <typename T> bool Stack<T>::isEmpty() {
return top == NULL;
}
template <typename T> Stack<T>::Stack() {
init();
}
template <typename T> Stack<T>::Stack(const Stack<T>& src) {
this->copy(src);
}
template <typename T> Stack<T>::~Stack() {
this->erase();
}
template <typename T> Stack<T>& Stack<T>::operator=(const Stack<T>& src) {
if (this != &src) {
this->erase();
this->init();
this->copy(src);
}
return *this;
}
template <typename T> size_t Stack<T>::size() {
return stackSize;
}
template <typename T> void Stack<T>::push(T& value) {
Node<T>* newNode = new Node<T>(value, this->top);
if (newNode) {
this->top = newNode;
stackSize++;
}
}
template <typename T> void Stack<T>::pop() {
if (!isEmpty()) {
Node<T>* remove = this->top;
this->top = this->top->next;
delete remove;
stackSize--;
}
}
template <typename T> T& Stack<T>::getTop() {
return top->value;
}