-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.h
More file actions
75 lines (73 loc) · 1.32 KB
/
Stack.h
File metadata and controls
75 lines (73 loc) · 1.32 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
#ifndef STACK_H
#define STACK_H
#include <iostream>
#define STACK_INIT_SIZE 100
template <typename T>
class Stack {
private:
T *Base;
T *Top;
int Size;//ÈÝÁ¿
public:
Stack() {
Base = Top = (T*)malloc(STACK_INIT_SIZE * sizeof(T));
if (Base == NULL) {
std::cout << "InsufficientDynamicMemory" << std::endl;
exit(1);
}
Size = STACK_INIT_SIZE;
}
Stack(Stack &S) {//É±´
Base = (T*)malloc(S.Size * sizeof(T));
if (Base == NULL) {
std::cout << "InsufficientDynamicMemory" << std::endl;
exit(1);
}
Top = Base + S.GetLength();
Size = S.Size;
for (int i = 0; i < S.GetLength(); i++) {
Base[i] = S.Base[i];
}
}
void ReAssign() {
T *newbase = (T*)realloc(Base, Size * 2 * sizeof(T));
if (newbase == NULL) {
std::cout << "InsufficientDynamicMemory" << std::endl;
exit(1);
}
Base = newbase;
Top = Base + Size - 1;
Size *= 2;
}
void Push(T x) {
if (GetLength() == Size - 1) {
ReAssign();
}
*Top = x;
Top++;
}
T Pop() {
if (Base == Top) {
std::cout << "TheStackIsEmpty" << std::endl;
exit(1);
}
else {
Top--;
return *Top;
}
}
bool IsEmpty() {
return Top == Base ? true : false;
}
int GetLength() {
return Top - Base;
}
T GetTop() {
if (Base == Top) {
std::cout << "TheStackIsEmpty" << std::endl;
exit(1);
}
return *(Top - 1);
}
};
#endif