/
15_数组实现大小固定的栈.cpp
76 lines (68 loc) · 1.47 KB
/
15_数组实现大小固定的栈.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
#include <iostream>
using namespace std;
/*
用数组结构实现大小固定栈
*/
class ArrayToStack{
public:
ArrayToStack(int size) {
m_p = (int *)malloc(sizeof(int) * size);
m_maxSize = size;
m_currentSize = 0;
}
int peek() {
if (m_currentSize == 0) {
cout << "数组长度为0" << endl;
return -1;
}
return m_p[m_currentSize - 1];
}
int push(int data) {
if (m_currentSize == m_maxSize) {
cout << "数组已满" << endl;
return -1;
}
m_p[m_currentSize] = data;
m_currentSize++;
return 0;
}
int pop() {
int ret = 0;
if (m_currentSize == 0) {
cout << "数组已空" << endl;
return ret;
}
ret = m_p[m_currentSize - 1];
m_currentSize--;
return ret;
}
~ArrayToStack() {
if (m_p != nullptr) {
free(m_p);
m_p = nullptr;
}
m_currentSize = 0;
m_maxSize = 0;
}
private:
int m_maxSize;
int m_currentSize;
int *m_p;
};
void test() {
ArrayToStack as(10);
for (int i = 0; i < 10; i++) {
//cout << as.peek() << endl;
as.push(i + 1);
cout << as.peek() << endl;
}
cout << "---------" << endl;
for (int i = 0; i < 11; i++) {
cout << as.peek() << endl;
cout << as.pop() << endl;
}
}
int main() {
test();
return 0;
}