-
Notifications
You must be signed in to change notification settings - Fork 267
/
DynamicStack.cpp
88 lines (75 loc) · 1.58 KB
/
DynamicStack.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
85
86
87
88
#include <iostream>
class Stack {
struct node {
int data;
node *next;
};
node *head = nullptr;
public:
static constexpr int emptyStack = -1;
void push(int value) {
node *newNode;
newNode = new node;
newNode->data = value;
if (head == nullptr) {
newNode->next = nullptr;
} else {
newNode->next = head;
}
head = newNode;
}
bool isEmpty() { return head == nullptr; }
int pop() {
int value = emptyStack;
if (!isEmpty()) {
value = head->data;
node *next, *at;
next = head->next;
at = head;
head = next;
delete at;
}
return value;
}
int showTop() {
int value = emptyStack;
if (!isEmpty()) {
value = head->data;
}
return value;
}
int size() {
int counter = 0;
node *temp;
temp = head;
while (temp->next != nullptr) {
counter++;
temp = temp->next;
}
counter++;
return counter;
}
};
int main() {
Stack stack;
int value;
for (int i = 0; i < 10; i++) {
std::cout << "Push: " << i + 1 << std::endl;
stack.push(i + 1);
}
for (int i = 0; i < 12; i++) {
value = stack.pop();
if (value != Stack::emptyStack) {
std::cout << "Pop: " << value << std::endl;
} else {
std::cout << "Stack is empty!" << std::endl;
}
}
for (int i = 0; i < 5; i++) {
std::cout << "Push: " << i + 1 << std::endl;
stack.push(i + 1);
}
std::cout << "Stack have " << stack.size() << " elements" << std::endl;
std::cout << stack.showTop() << " is the top element of stack" << std::endl;
return 0;
}