static.h
#define STATIC_INIT_SIZE 100
#define STATICINCREMENT 10#define ERROR 0#define OK 1typedef struct {int *base;//定义栈底
int *top;//定义栈顶元素 int staticsize;}SqStatic;typedef int Status;
//初始化一个空栈
Status InitStatic(SqStatic *S);//销毁栈
Status DestroyStatic(SqStatic *S);//清空栈
Status ClearStatic(SqStatic *S);//判断栈是否为空
Status StaticEmpty(SqStatic S);//获取栈的长度
int StaticLength(SqStatic S);//获取栈顶元素的值
Status GetTop(SqStatic S, int *e);//向栈中加入元素
Status Push(SqStatic *S,int e);//删除栈顶元素并返回元素值
Status Pop(SqStatic *S, int *e);void conversion(SqStatic *S)
StaticRealize.c
#include "stdlib.h"
#include "stdio.h"#include "static.h" Status InitStatic(SqStatic *S) {//设置初始栈的大小
S->base = (int *)malloc(sizeof(int)*STATIC_INIT_SIZE); if (!S->base) { exit(0); } S->top = S->base;//空栈 s->top=s->base *(S->top) = 0;//主要用来判断是否为空栈 S->staticsize = STATIC_INIT_SIZE;//栈的初始长度为100return OK;
}//获取栈顶元素的值Status GetTop(SqStatic S, int *e) {SqStatic q;
q = S; //返回栈顶元素需要判断栈是否为空栈 if (S.base == S.top) return ERROR;*e = *(q.top - 1);
return OK;
}
//元素的进栈
Status Push(SqStatic *S,int e) { if ((S->top-S->base)>=S->staticsize) {S->base = (int *)realloc(S->base,(STATICINCREMENT+STATIC_INIT_SIZE)*sizeof(int));
} *(S->top) = e;S->top++;
return OK;}
Status Pop(SqStatic *S,int *e) {if (S->top == S->base)return ERROR;
S->top--; *e = *(S->top);return OK;
}
Status StaticEmpty(SqStatic S) {
if (*(S.top) == 0) {return OK;
} return ERROR;} //返回栈中元素的个数int StaticLength(SqStatic S) {return S.top - S.base;
}
//十进制转换为二进制
void conversion(SqStatic *S) {
printf("请输入要转换的整数\n");
int n; int e; scanf("%d",&n); while (n) { int c = n % 2; Push(S,c); n =n/2; } printf("输出转换后的二进制\n"); while (!StaticEmpty(*S)) { Pop(S,&e);printf("%d",e);
}
printf("\n"); }
StaticFunction.c
#include "stdio.h"
#include "stdlib.h"#include "static.h"//主函数void main() { //初始化一个空栈 SqStatic S; int e,f;InitStatic(&S);
// printf("判断栈是否为空栈%d\n", StaticEmpty(S)); Push(&S,1); GetTop(S, &e); printf("栈顶元素为%d\n", e); Push(&S,2); GetTop(S, &e); printf("栈顶元素为%d\n", e); Push(&S,3); GetTop(S, &e); printf("栈顶元素为%d\n", e);Push(&S,4);
GetTop(S, &e); printf("栈顶元素为%d\n",e);Pop(&S, &f);
printf("弹出的值为%d\n",f);
Pop(&S, &f);
//10进制转换为二进制
conversion(&S);
printf("弹出的值为%d\n", f);
printf("判断栈是否为空栈%d\n", StaticEmpty(S));
printf("栈的长度为%d\n",StaticLength(S));
}