• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Crazy丶
享受现在的每一天........
博客园    首页    新随笔    联系   管理    订阅  订阅

栈的顺序存储实现

顺序存储结构实现栈

#include<stdio.h>
#include<stdlib.h>

#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define FALSE 0
#define INIT_SIZE 20
#define INCREMENT_SIZE 10
typedef int Elemtype;
typedef int Status;

typedef struct {
Elemtype *base;//栈尾指针
Elemtype *top;//栈顶指针
int size;
}SqStack;
Status InitStack(SqStack *S)
{
S->base = (Elemtype *)malloc(INIT_SIZE*sizeof(Elemtype));
if(!S->base)
{
exit(OVERFLOW);
}
S->top=S->base;
S->size=INIT_SIZE;
return OK;
}

Status Push(SqStack *S,Elemtype e)
{
if((S->top-S->base)/sizeof(Elemtype)>=S->size)
{
S->base=(Elemtype *)realloc(S->base,(S->size+INCREMENT_SIZE)*sizeof(Elemtype));
if(!S->base)
{
exit(OVERFLOW);
}
S->top=S->base+S->size*sizeof(Elemtype);
S->size+=INCREMENT_SIZE;
}
*S->top=e;
S->top+=sizeof(Elemtype);
return OK;

}

Status Pop(SqStack *S,Elemtype *e)
{
if(S->top==S->base)
{
printf("The stack is empty\n");
return ERROR;
}
else
{
S->top-=sizeof(Elemtype);
*e=*S->top;
return OK;
}
}
Status TraverseStack(SqStack *S)
{
while(S->top>S->base)
{
printf("%d\n",*S->base);
S->base+=sizeof(Elemtype);
}
return OK;
}
int main()
{
int i;
int a;
SqStack S;
int ret=InitStack(&S);
if(ret)
{
printf("init_success\n");
}
else
{

printf("init_error\n");
}
for(i=0;i<10;i++)
{
Push(&S,i+1);

}

TraverseStack(&S);

return 0;
}

posted @ 2015-06-06 13:45  Crazy丶  阅读(307)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3