#include<stdio.h>
#include<stdlib.h>
#define stack_initSize 100
#define stack_incrementSize 10
typedef struct{
int * stackdata;
int top;
int stacksize;
}seqStack;
void InitStack(seqStack *S){//初始化栈
if(!S) {printf("顺序栈无效
"); return;}
S->stackdata=(int *)malloc(stack_initSize*sizeof(int));
S->top=0;
S->stacksize=stack_initSize;
}
void InStack(seqStack * S,int e){//进栈
int * newstack;
if(!S) {printf("顺序栈无效
"); return;}
if(S->top==S->stacksize){
newstack=(int*)realloc(S->stackdata,(S->stacksize+stack_incrementSize)*sizeof(int));
if(!newstack) { printf("内存分配错误
");return;}
S->stackdata=newstack;
S->stacksize=S->stacksize+stack_incrementSize;
}
S->stackdata[S->top++]=e;
}
void OutStack(seqStack *S){//出栈
int e;
if(!S) {printf("顺序栈无效
"); return;}
if(S->top==0) {printf("栈为空
"); return;}
e=S->stackdata[--S->top];
printf("%d",e);
}
void TraversalStack(seqStack * S){//遍历栈
int i;
for(i=0;i<S->top;i++){
printf("%d ",S->stackdata[i]);
}
printf("
");
}
void LengthStack(seqStack *S){//栈长
printf("栈的长度为%d
",S->top);
}
void IsEmpty(seqStack *S){//判断是否为空
if(!S) {printf("顺序栈无效
"); return;}
if(S->top==0) printf("栈为空
");
else
printf("栈不为空
");
}
int main(void){
seqStack *S=(seqStack*)malloc(sizeof(seqStack));
int i,x,z;
int y=1;
while(y){
printf("***********************
");
printf("--1.初始化栈--
");
printf("--2.进栈--
");
printf("--3.出栈--
");
printf("--4.遍历栈--
");
printf("--5.求栈长--
");
printf("--6.栈是否为空--
");
printf("--7.进制转换--
");
printf("--8.退出--
");
printf("--请选择你要进行的操作--
");
scanf("%d",&i);
switch(i){
case 1:InitStack(S);printf("栈已经初始化
");break;
case 2: printf("请输入你要进栈的元素
");scanf("%d",&x);InStack(S,x);printf("%d已经进栈
",x);break;
case 3: OutStack(S); printf("
已经出栈
");break;
case 4: TraversalStack(S);break;
case 5: LengthStack(S);break;
case 6: IsEmpty(S);break;
case 7:
printf("请输入你要转换的10进制数:
");
scanf("%d",&z);
InitStack(S);
while(z){
InStack(S,z%2);
z=z/2;
}
printf("转换结果为:
");
while(S->top!=0){
OutStack(S);
}
printf("
");
break;
case 8: y=0;printf("已退出
");break;
}
}
return 0;