码迷,mamicode.com
首页 > 编程语言 > 详细

C语言栈的实现

时间:2017-09-22 19:06:12      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:返回   push   eof   获取   stdio.h   ini   get   函数   初始化   

static.h

 

#define STATIC_INIT_SIZE 100
#define STATICINCREMENT 10
#define ERROR 0
#define OK 1
typedef 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);

 

 

StaticRealize.c

 

#include "stdlib.h"
#include "stdio.h"
#include "static.h"


Status InitStatic(SqStatic *S) {

//设置初始栈的大小
S->base = (SqStatic *)malloc(sizeof(SqStatic)*STATIC_INIT_SIZE);

if (!S->base) {
exit(0);
}
S->top = S->base;//空栈 s->top=s->base
*(S->top) = 0;//主要用来判断是否为空栈
S->staticsize = STATIC_INIT_SIZE;//栈的初始长度为100

return 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 = (SqStatic *)realloc(S->base,(STATICINCREMENT+STATIC_INIT_SIZE)*sizeof(SqStatic));
}
*(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;
}

 

 

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);

printf("弹出的值为%d\n", f);

printf("判断栈是否为空栈%d\n", StaticEmpty(S));

printf("栈的长度为%d\n",StaticLength(S));


}

 

C语言栈的实现

标签:返回   push   eof   获取   stdio.h   ini   get   函数   初始化   

原文地址:http://www.cnblogs.com/paulversion/p/7576079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!