자료구조
Stack 구현 (c++)
연결리스트
2020. 8. 25. 19:15
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
|
#include<iostream>
class Stack {
int* data;
int s_size;
int s_top;
public:
Stack(int n);
void push(int n);
void pop();
int top();
bool is_full();
bool empty();
void print();
~Stack();
};
Stack::Stack(int n) : data(new int[n]), s_size(n), s_top(-1) {}
void Stack::push(int n) {
if (!is_full()) {
data[++s_top] = n;
}
else {
std::cout << "스택이 가득 찼습니다" << std::endl;
}
}
void Stack::pop() {
if (!empty()) {
s_top--;
}
else {
std::cout << "스택이 비어있습니다" << std::endl;
}
}
int Stack::top() {
if (!empty()) {
return data[s_top];
}
else {
return NULL;
}
}
bool Stack::is_full() {
if (s_top + 1 == s_size) {
return true;
}
else {
return false;
}
}
bool Stack::empty() {
if (s_top < 0) {
return true;
}
else {
return false;
}
}
void Stack::print() {
for (int i = 0; i <= s_top; i++) {
std::cout << data[i] << std::endl;
}
}
Stack::~Stack() {
delete[] data;
}
int main() {
Stack s(5);
s.push(1);
s.push(3);
s.push(5);
s.push(7);
s.push(9);
s.pop();
s.pop();
std::cout << "top : " << s.top() << std::endl;
s.print();
}
|
cs |