码迷,mamicode.com
首页 > 其他好文 > 详细

栈的顺序存储实现

时间:2015-06-06 14:52:56      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:

#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;
}

栈的顺序存储实现

标签:

原文地址:http://www.cnblogs.com/loveyan/p/4556536.html

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