数据结构—栈的顺序的实现
#include<stdio.h>
#include<stdlib.h>
#define Stack_size 100 //栈的初始容量
#define stackIncrease 10 //每次的增量
typedef int Elemtype;
typedef struct{
Elemtype *base;
Elemtype *top;
int stacksize;
}Sqstack;
bool InitStack(Sqstack &S){ //初始化栈
S.base = (Elemtype *)malloc(Stack_size*sizeof(Elemtype));
if(!S.base)
return false;
S.top = S.base;
S.stacksize = Stack_size;
return true;
}
void ClearStack(Sqstack &S){ //清空栈的元素 实际上只移动了一下指针
S.top = S.base;
}
bool StackEmpty(Sqstack S){ //判断栈是否为空
if(S.base == S.top)
return true;
else
return false;
}
int StackLength(Sqstack S){ //返回栈的长度
return S.top - S.base;
}
bool GetTop(Sqstack &S, Elemtype &e){ //得到栈顶元素, 并用e返回
if(S.base == S.top) //栈为空
return false;
e = *(S.top - 1);
return true;
}
bool Push(Sqstack &S, Elemtype e){ //将元素e入栈
if(S.top - S.base >= S.stacksize){
S.base = (Elemtype *)realloc(S.base, (S.stacksize + stackIncrease)*sizeof(Elemtype));
if(!S.base)
return false;
S.top = S.base + S.stacksize;
S.base += stackIncrease;
}
*S.top = e;
S.top++;
//*(S.top++) = e; //这两条语句可以合并
return true;
}
bool Pop(Sqstack &S, Elemtype &e){ //删除栈顶元素, 并用e返回
if(S.base == S.top)
return false;
e = *(--S.top);
return true;
}
int main(){
Sqstack S;
int e;
if(InitStack(S) == true){
printf("栈已经初始化好啦,请输入你想往进放的元素:\n");
printf("温馨提示:输入-1代表停止输入\n");
}
while(scanf("%d", &e) && e != -1){
Push(S, e);
}
printf("栈的长度是:%d\n", StackLength(S));
printf("请输入你想要进行的操作序号:\n");
printf("1:添加元素,2:删除栈顶元素,3:取栈顶元素,4:判断栈是否为空,\n5:返回栈的长度,6:清空栈,7:退出\n");
int n;
while(scanf("%d", &n) && n != 7){
switch(n){
case 1:
printf("请输入你想添加的元素:");
scanf("%d", &e);
if(Push(S, e) == true)
printf("添加成功\n");
else
printf("添加失败\n");
break;
case 2:
if(Pop(S, e) == true){
printf("删除成功,删除的元素是:%d\n", e);
}
else
printf("删除失败\n");
break;
case 3:
if(GetTop(S, e) == true)
printf("栈顶元素是:%d\n", e);
else
printf("操作失败\n");
break;
case 4:
if(StackEmpty(S) == true)
printf("栈为空\n");
else
printf("栈不为空\n");
break;
case 5:
printf("栈的长度是:%d\n", StackLength(S));
break;
case 6:
ClearStack(S);
printf("清空成功\n");
break;
default:
printf("输入有误,请重新输入\n");
break;
}
}
printf("谢谢你的使用!\n");
return 0;
}
![Image 1][]
[Image 1]:
还没有评论,来说两句吧...