用数组实现一个栈

用数组实现一个栈

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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#include <iostream>
//栈的数组实现
using namespace std;
#define MAXSIZE 10;

template<class T>
class Stack
{
public:
//默认构造函数
Stack();
Stack(size_t maxElements);
Stack(T data[], size_t maxElements);
~Stack();

//入栈
void Push(T data);

//出站并返回
T Pop();

//返回栈顶元素
T Top();

//判断是否为空栈
bool isEmpty();

//栈是否已满
bool isFull();

//清空栈
void Clear();

//获得栈元素个数
size_t GetSize();
private:
//栈标指示器
size_t top;

//数组
T *arrays;

//栈的容量
size_t maxSize;
};

template<class T>
Stack<T>::Stack() : maxSize(MAXSIZE), top(-1)
{
arrays = new T[maxSize];
if (arrays == NULL)
{
cout << "动态分配内存失败";
exit(1);
}
}

template<class T>
Stack<T>::Stack(size_t maxElements) : maxSize(maxElements), top(-1)
{
arrays = new T[maxSize];
if (arrays == NULL)
{
cout << "动态分配内存失败";
exit(1);
}
}

template<class T>
Stack<T>::Stack(T data[], size_t maxElements) : maxSize(maxElements), top(-1)
{
arrays = new T[maxSize];//创建存储栈的数组
if (arrays == NULL)
{
cout << "动态分配内存失败";
exit(1);
}
for (size_t i = 0; i < maxSize; i++)
{
arrays[i] = data[i];
}
top += maxSize;
}

template<class T>
Stack<T>::~Stack()
{
delete[] arrays;
}

template<class T>
void Stack<T>::Push(T data)
{
if (isFull())
{
throw runtime_error("Full stack");
}
else
{
top++;//指向栈顶
arrays[top] = data;
}
}

template<class T>
T Stack<T>::Pop()
{
if (isEmpty())
{
throw runtime_error("No elements in the stack");
}
else
{
T data = arrays[top];
top--;
return data;
}
}

template<class T>
T Stack<T>::Top()
{
if (isEmpty())
{
throw runtime_error("No elements in the stack");
}
else
{
return arrays[top];
}
}

template<class T>
bool Stack<T>::isEmpty()
{
return top == -1;
}

template<class T>
bool Stack<T>::isFull()
{
return top == maxSize - 1;
}

template<class T>
void Stack<T>::Clear()
{
while (Top != -1)
{
Top--;
}
}

template<class T>
size_t Stack<T>::GetSize()
{
return top + 1;
}

int main()
{
try//异常捕获
{
int a[6] = { 1, 2, 3, 4, 5, 6 };
Stack<int> s(a, 6);
s.Pop();
s.Push(7);
while (!s.isEmpty())
{
cout << s.Pop() << " ";
}
cout << endl;
}
catch (exception e)
{
cout << e.what() << endl;
}
system("pause");
return 0;
}
-------------本文结束,感谢您的阅读-------------