第一次写博客,写的是关于栈的建立,写的不好多多见谅啊
这个建栈啊就是一种数据结构,是那种先进后出的,先进来的数据放在最下面,最后进来的数据放在最上面,还有一种数据结构是那种先进先出型的,就像水管一样,先进去的先出来
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 100
#define Increasement 20
typedef struct
{
int *top;
int *base;
int size;
}stack;
stack *initstack(stack *s) //初始化一个栈
{
s->base=(int *)malloc(Maxsize*sizeof(int));
if(s->base==NULL)
{
printf("error");
exit(0);
}
else
{
s->top=s->base;
}
s->size=Maxsize;
}
stack *destory(stack *s) //销毁栈
{
s->top=s->base;
free(s->base);
s->top=NULL; //这两个是防止出现野指针
s->base=NULL;
return s;
}
int empty(stack *s) //是否为空栈
{
if(s->top==s->base)
return 1;
else
return 0;
}
int gettop(stack *s,int e) //获得栈顶
{
if(empty(s))
{
printf("the stack is empty\n");
}
else
{
s->top--;
e=*s->top;
return e;
}
}
int clearstack(stack *s) //清楚栈
{
s->top=s->base;
s->size=0;
return 1;
}
void display(stack *s) //显示栈元素
{
if(empty(s))
{
printf("empty\n");
}
else
{
while(s->top!=s->base)
{
printf("%d",*(--s->top));
}
}
}
int push(stack *s,int e) //进栈
{
if((s->top-s->base)>Maxsize)
{
s->base=(int *)realloc(s->base,(Maxsize+Increasement)*sizeof(int));
if(s->base==NULL)
{
printf("error");
return 0;
}
s->size=Maxsize;
*(s->top++)=e;
return 1;
}
else
{
*s->top=e;
s->top++;
return 1;
}
}
int pop(stack *s,int e) //出栈
{
if(empty(s))
{
printf("stack is empty");
return 0;
}
else
{
e=*(--s->top);
return 1;
}
}
void main()
{
int i;
stack s;
initstack(&s);
for(i=0;i<5;i++)
{
if(push(&s,i))
{
printf("%d is pushed successfully\n",i);
}
else
{
printf("error");
}
}
display(&s);
system("pause");
}