实验结构数据四 栈的顺序存储
一、基础篇
1.实现栈的基本 操作
全部代码
stack.h
#define STACK_INIT_SIZE 100 //栈存储空间初始化分配量
#define STACKINCREAMENT 10 //栈存储空间分配的增量
#define LISTINCREAMENT 10 //线性表存储空间的分配增量
//------------------销毁栈表
if(DestroyStack(s))
printf("栈表已销毁!n");
return 0;
}
一个程序的构成,主要需要三个部分,stack.h,stack.cpp,和main.cpp
在头文件也就是stack.h中,对线性表的存储空间进行增量分配
而且,在栈的定义中,需要两个指针,一个头指针,一个尾指针,还要对单位进行定义,栈是以元素为单位的。
栈的基本操作
1.初始化栈
stack.h
bool InitStack(SqStack &S);
stack.cpp
void InitData(SqStack &S){
for(int j=0;j<5;j++){
S.top++;
*(S.top)=j;
}
}
main.cpp
if(InitStack(s))
printf("初始化成功!n");
InitData(s);
2.存入初始数据
stack.h
void InitData(SqStack &S);
stack.cpp
void InitData(SqStack &S){
for(int j=0;j<5;j++){
S.top++;
*(S.top)=j;
}
}
此处主函数中没有关于存入初始数据的相关代码,因为主函数只负责调用
3.判断是否为空
stack.h
bool StackEmpty(SqStack &S);
stack.cpp
bool StackEmpty(SqStack &S){
if(S.base==S.top&&S.top==NULL)
return true;
else
return false;
}
main.cpp
if(StackEmpty(s))
printf("栈表为空!n");
else
printf("栈表不为空!n");
4.寻求长度
stack.h
int StackLength(SqStack S);
stack.cpp
int StackLength(SqStack S){
int length=0;
while(S.base!=S.top){
++length;
++S.base;
}
return length;
}
main.cpp
printf("栈表长度为:%dn",StackLength(s));
5.求栈顶元素
stack.h
void GetTop(SqStack S,int &e);
stack.cpp
void GetTop(SqStack S,int &e){
e=*(S.top);
}
main.cpp
GetTop(s,e);
printf("栈顶元素为:%dn",e);
6.插入元素
stack.h
bool Push(SqStack &S,int &e);
stack.cpp
bool Push(SqStack &S,int &e){
if((S.top-S.base)/sizeof(int)>=S.stacksize)
return false;
++S.top;
*(S.top)=e;
return true;
}
main.cpp
printf("请输入需要插入的元素值:");
scanf("%d",&e);
if(Push(s,e))
printf("插入成功!n");
7.删除栈顶元素
stack.h
bool Pop(SqStack &S,int &e);
stack.cpp
bool Pop(SqStack &S,int &e){
if(S.base==S.top)
return false;
e=*(S.top);
S.top--;
return true;
}
main.cpp
if(Pop(s,e))
printf("删除成功!n");
8.清空栈表
stack.h
bool ClearStack(SqStack &S);
stack.cpp
bool ClearStack(SqStack &S){
if(S.base==S.top)
return false;
S.top=S.base;
return true;
}
清空栈表也没有主函数相对应代码
9.销毁栈表
stack.h
bool DestroyStack(SqStack &S);
stack.cpp
bool DestroyStack(SqStack &S){
if(!S.base)
return false;
free(S.base);
return true;
}
main.cpp
if(DestroyStack(s))
printf("栈表已销毁!n");



