-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.hpp
More file actions
110 lines (89 loc) · 2.16 KB
/
Stack.hpp
File metadata and controls
110 lines (89 loc) · 2.16 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
#ifndef STACK_HPP
#define STACK_HPP
#include <iostream>
template <typename T>
class Stack {
private:
struct Node {
T value;
Node* next;
Node(T val) : value(val), next(nullptr) {}
};
Node* topNode;
int nrElem;
public:
Stack() {
topNode = nullptr;
nrElem = 0;
}
~Stack() {
while (topNode != nullptr) {
Node* temp = topNode;
topNode = topNode->next;
delete temp;
}
}
bool emptyStack() const {
return topNode == nullptr;
}
void push(T newValue) {
Node* elem = new Node(newValue);
elem->next = topNode;
topNode = elem;
nrElem++;
}
bool pop() {
if (emptyStack()) return false;
Node* tmp = topNode;
topNode = topNode->next;
delete tmp;
nrElem--;
return true;
}
bool peek(T& value) const {
if (emptyStack()) return false;
value = topNode->value;
return true;
}
void printStack() const {
Node* tmp = topNode;
while (tmp != nullptr) {
std::cout << tmp->value << " ";
tmp = tmp->next;
}
std::cout << "\n";
}
int getNrElem() const {
return nrElem;
}
bool contains(T target) const {
Node* tmp = topNode;
while (tmp != nullptr) {
if (tmp->value == target) return true;
tmp = tmp->next;
}
return false;
}
void sortStack() {
if (emptyStack() || topNode->next == nullptr) return;
Stack<T> tempStack;
while (!emptyStack()) {
T tempValue;
peek(tempValue);
pop();
T topTempValue;
while (!tempStack.emptyStack() && tempStack.peek(topTempValue) && topTempValue > tempValue) {
push(topTempValue);
tempStack.pop();
}
tempStack.push(tempValue);
}
while (!tempStack.emptyStack()) {
T tempValue;
tempStack.peek(tempValue);
tempStack.pop();
push(tempValue);
}
}
};
#endif