-
Notifications
You must be signed in to change notification settings - Fork 2
/
stack.cpp
93 lines (88 loc) · 1.49 KB
/
stack.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
89
90
91
92
93
#include <iostream>
using std::cin;
using std::cout;
using std::freopen;
class Elem {
private:
Elem* next;
int val;
public:
/* constructor */
Elem(int val) {
this->val = val;
this->next = nullptr;
}
/* check next element */
bool hasNext() {
if (this->next != nullptr) {
return true;
} else {
return false;
}
}
/* set next element */
void setNext(Elem* next) {
this->next = next;
}
/* get pointer */
Elem* getNext() {
return this->next;
}
/* set value */
void setVal(int val) {
this->val = val;
}
/* get value */
int getVal() {
return this->val;
}
};
class Stack{
private:
Elem* first; //stack front
public:
/* constructor */
Stack() {
this->first = nullptr;
}
/* destructor */
~Stack() {
while (!this->is_empty()) {
this->pop();
}
}
/* push new element */
void push(int val){
if (this->first == nullptr) {
this->first = new Elem(val);
} else {
Elem* tmp = this->first;
this->first = new Elem(val);
this->first->setNext(tmp);
}
}
/* get and delete front element */
int pop(){
if (!this->is_empty()) {
Elem* tmp = this->first;
this->first = this->first->getNext();
int val = tmp->getVal();
delete tmp;
return val;
} else return -1;
}
/* check for items */
bool is_empty() {
if (this->first != nullptr) {
return false;
} else {
return true;
}
}
};
int main() {
Stack* st= new Stack();
st->push(5);
cout<<st->pop();
return 0;
}