-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
106 lines (85 loc) · 2.13 KB
/
stack.h
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
#pragma once
#include <stdexcept>
template<typename T>
class LinkedList {
struct Node {
explicit Node(T aElement) : element(aElement) {};
const T element;
Node *nextNode = nullptr;
Node *prevNode = nullptr;
};
Node *front = nullptr;
Node *back = nullptr;
public:
LinkedList() = default;
LinkedList(const LinkedList &obj) {
if (obj.empty()) return;
Node *node = obj.front;
push_back(node->element);
while (node->nextNode != nullptr) {
node = node->nextNode;
push_back(node->element);
}
};
void push_back(T element) {
Node *newNode = new Node(element);
if (empty()) {
front = newNode;
back = newNode;
return;
}
Node *oldBack = back;
oldBack->nextNode = newNode;
newNode->prevNode = oldBack;
back = newNode;
};
T pop_back() {
if (empty()) {
throw std::out_of_range("There are no elements in the list");
}
if (back->prevNode == nullptr) {
front = nullptr;
}
T value = back->element;
Node *newBack = back->prevNode;
if (newBack != nullptr) newBack->nextNode = nullptr;
delete back;
back = newBack;
return value;
};
[[nodiscard]] const T &peek_back() const {
if (empty()) {
throw std::out_of_range("There are no elements in the list");
}
return back->element;
};
[[nodiscard]] bool empty() const {
return front == nullptr;
}
~LinkedList() {
if (empty()) return;
Node *node = front;
Node *next;
while (node != nullptr) {
next = node->nextNode;
delete node;
node = next;
}
}
};
template<typename T>
class Stack : private LinkedList<T> {
public:
void push(T element) {
this->push_back(element);
};
T pop() {
return this->pop_back();
};
T peek() {
return this->peek_back();
};
bool empty() {
return LinkedList<T>::empty();
}
};