栈:数组实现
结构描述:
#define MAX 100
typedef int DataType;
class SeqStack {
public:
DataType * A;
int Top;
void Init();
void Push(DataType X);
void Pop();
DataType GetTop();
void MakeEmpty();
bool IsEmpty();
bool IsFull();
};
初始化
把栈顶置为 -1
并给指针 A
分配内存。
void SeqStack::Init() {
Top = -1;
A = (DataType *)malloc(sizeof (DataType) * MAX);
}
判空、判满
栈空: Top == -1
栈满: Top = MAX - 1
bool SeqStack::IsEmpty() {
return Top == -1;
}
bool SeqStack::IsFull() {
return Top == MAX - 1;
}
入栈
- 栈为满:报错
- 栈不满:栈顶指针
+ 1
,把入栈的数据放在栈顶处。
void SeqStack::Push(DataType X) {
if (IsFull()) {
cout << "Stack Is Full!" << endl;
exit(-1);
}
else {
Top++;
A[Top] = X;
}
}
出栈
- 栈空:报错
- 非空:栈顶指针
-1
void SeqStack::Pop() {
if (IsEmpty()) {
cout << "Stack Is Empty!" << endl;
exit(-1);
}
else {
Top--;
}
}
获取栈顶元素
- 栈空:报错
- 非空:返回元素
DataType SeqStack::GetTop() {
if (IsEmpty()) {
cout << "Stack Is Empty!" << endl;
exit(-1);
}
else {
return A[Top];
}
}
摧毁
如果栈不为空,就一直出栈,直至栈空
void SeqStack::MakeEmpty() {
while (!IsEmpty()) {
cout << A[Top] << " ";
Pop();
cout << "Has Been Poped!" << endl;
}
cout << "Stack Has Been Completed!" << endl;
}
标签:SeqStack,cout,实现,void,DataType,IsEmpty,数组,Top
From: https://www.cnblogs.com/codels/p/18309488