实现一个int型的顺序栈,定义好存储结构,并完成这些基本操作:Init,Push,Pop,GetTop,Traverse,Clear,Destroy, IsEmpty, IsFull。请自行设计main函数以测试各个基本操作。
#include <iostream>
using namespace std;
#define InitSize 100
#define StackIncrement 50
typedef int ElemType;
typedef struct { //顺序栈定义
ElemType* elem; //栈数组
int top; //或ElemType*,栈顶指针
int size; //栈大小
} SeqStack;
int InitStack(SeqStack& S) { //初始化
S.elem = new ElemType[InitSize];
if (!S.elem) exit(1);
S.top = -1;
S.size = InitSize;
return 1;
}
int IsEmpty(const SeqStack& S) {
//判断栈是否空,空则返回1,否则返回0
return S.top == -1;
}
int IsFull(const SeqStack& S) {
//判断栈是否,满则返回1,否则返回0
return S.top == S.size;
}
int Push(SeqStack& S, ElemType &e) {
//若栈满返回0, 否则新元素 e 进栈并返回1
if (IsFull(S)) return 0;
S.top++; //先移动指针
S.elem[S.top] = e; //再加入新元素
return 1;
}
int Pop(SeqStack& S, ElemType& e) {
//若栈空返回0, 否则栈顶元素退出到e并返回1
if (IsEmpty(S)) return 0;
e = S.elem[S.top]; S.top--;
return 1;
}
int GetTop(const SeqStack& S, ElemType& e) {
//若栈空返回0, 否则栈顶元素读到e并返回1
if (IsEmpty(S)) return 0;
e = S.elem[S.top];
return 1;
}
void OverFlow(SeqStack& S) { //栈满处理
int newSize = S.size + StackIncrement;
ElemType* newS = new ElemType[newSize];
if (!newS) exit(1);
ElemType* src = S.elem,
* obj = newS;
for (int i = 0; i < S.size; i++)
*obj++ = *src++; //向新数组传送数据
delete[]S.elem; //释放老数组
S.elem = newS; //新数组作为栈数组
S.size = newSize; //新数组大小
} //栈顶指针不变
void Traverse(const SeqStack& S) {//遍历栈
if (IsEmpty(S)) cout << "空表,无法遍历" << endl;
for (int i = 0; i <= S.top; i++) {
cout << S.elem[i] << endl;
}
}
int Clear(SeqStack& S) {//清空栈
if (IsEmpty(S))return 1;
S.top = -1;
return 1;
}
int Destroy(SeqStack& S) {//销毁栈
free(S.elem);
S.elem = NULL;
S.size = 0;
S.top = NULL;
return 1;
}
int main() {
cout << "=====定义一个栈S=====" << endl;
SeqStack S;
int e;
cout << "=====初始化该栈S=====" << endl;
InitStack(S);
cout << "=====判断S是否是空栈:=====" << endl;
if (IsEmpty(S)) {
cout << "S是空栈" << endl;
}
else {
cout << "S不是空栈" << endl;
}
cout << "=====入栈1,2,3,4,5=====" << endl;
for (int i = 1; i <= 5; i++) {
Push(S, i);
}
cout << "=====判断S是否是满栈:=====" << endl;
if (IsFull(S)) {
cout << "S是满栈" << endl;
}
else {
cout << "S不是满栈" << endl;
}
cout << "=====取栈顶的值并打印:=====" << endl;
GetTop(S, e);
cout << "栈顶的值为:" << e << endl;
cout << "=====遍历该栈:=====" << endl;
Traverse(S);
cout << "=====出栈一个值:=====" << endl;
Pop(S, e);
cout << "=====遍历该栈:=====" << endl;
Traverse(S);
cout << "=====取栈顶的值并打印:=====" << endl;
GetTop(S, e);
cout << "栈顶的值为:" << e << endl;
cout << "=====清空该栈=====" << endl;
Clear(S);
cout << "=====遍历该栈:=====" << endl;
Traverse(S);
cout << "=====销毁该栈:=====" << endl;
if (Destroy(S)) {
cout << "销毁栈成功" << endl;
}
else {
cout << "销毁栈失败" << endl;
}
}