-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_stack.h
More file actions
120 lines (95 loc) · 1.97 KB
/
array_stack.h
File metadata and controls
120 lines (95 loc) · 1.97 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#ifndef H_ARRAY_STACK_H
#define H_ARRAY_STACK_H
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#define internal_allocate malloc
#define internal_deallocate free
typedef struct internal_hook {
void* (*allocate)(size_t size);
void (*deallocate)(void *pointer);
}internal_hook;
template<class T>
class ArrayStack {
public:
ArrayStack(int size = 10);
~ArrayStack();
void StackPush(T data);
T StackPop();
T StackTop();
bool IsEmpty();
T GetPosStackItme(int pos);
static internal_hook m_hook;
private:
T* m_item;
int m_capacity;
int m_size;
};
template<class T>
internal_hook ArrayStack<T>::m_hook = { internal_allocate, internal_deallocate};
/*
1. 默认参数在声明时指定
2. 类模板构造析构函数实现放在头文件中
*/
template<class T>
ArrayStack<T>::ArrayStack(int size)
:m_item(nullptr), m_capacity(size), m_size(0)
{
m_item = new T[size];
if (nullptr == m_item) {
std::cout << "allocate error\n";
}
}
template<class T>
ArrayStack<T>::~ArrayStack()
{
if (m_item) {
delete[] m_item;
m_item = nullptr;
}
}
template<class T>
void ArrayStack<T>::StackPush(T data)
{
assert(m_item);
if (m_size >= m_capacity) {
std::cout<< "stack is full!\n";
return ;
}
m_item[m_size++] = data;
}
template<class T>
bool ArrayStack<T>::IsEmpty()
{
return m_size == 0;
}
template<class T>
T ArrayStack<T>::StackPop()
{
assert(m_item);
if (m_size <= 0) {
std::cout << "stack is empty\n";
return 0;
}
return m_item[--m_size];
}
template<class T>
T ArrayStack<T>::StackTop()
{
assert(m_item);
if (m_size <= 0) {
std::cout << "stack is empty\n";
return 0;
}
return m_item[m_size - 1];
}
template<class T>
T ArrayStack<T>::GetPosStackItme(int pos)
{
assert(m_item);
if (pos < 0 || pos > m_capacity) {
return 0;
}
return m_item[pos - 1];
}
#endif