-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstack.hpp
119 lines (96 loc) · 1.93 KB
/
stack.hpp
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
#ifndef STACK_H
#define STACK_H
#include "stdint.h"
#include "node.hpp"
class Stack
{
public:
Node* head;
Node* tail;
Stack () {
head = nullptr;
tail = nullptr;
}
~Stack() {
empty();
}
void push (uint8_t val) {
if (head == nullptr) {
head = new Node(val);
tail = head;
} else {
tail->next = new Node(val);
tail = tail->next;
}
}
bool pop (uint8_t* val) {
if (head == nullptr)
return false;
if (head == tail) {
(*val) = tail->data;
delete tail;
head = tail = nullptr;
return true;
}
Node* curr = head;
while (curr->next != tail)
curr = curr->next;
(*val) = tail->data;
delete tail;
tail = curr;
curr->next = nullptr;
return true;
}
bool top (uint8_t * val) {
if (head == nullptr)
return false;
Node* curr = head;
while (curr->next != tail)
curr = curr->next;
(*val) = tail->data;
tail = curr;
return true;
}
void foreach (void (*callback)(uint8_t))
{
if (head == nullptr) return;
Node *curr = head;
while (curr->next != nullptr)
{
(*callback)(curr->data);
curr = curr->next;
}
(*callback)(curr->data);
}
void empty () {
if (head == nullptr)
return;
Node *curr = head;
Node *before;
while (curr->next != nullptr)
{
before = curr;
curr = curr->next;
delete before;
}
delete curr;
head = nullptr;
}
bool item (uint8_t index, uint8_t* val) {
Node* curr = head;
if (index < 0) return false;
while (index != 0) {
index--;
if (curr != nullptr)
curr = curr->next;
else
return false;
}
if (curr != nullptr){
(*val) = curr->data;
return true;
}
return false;
}
};
#endif