数据结构之数组实现栈


#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define sqstack_Initsize 20
#define sqstack_Increase_size 20
#define OK 1
#define ERROR 0
typedef struct
{
int *base;
int *top;
int sqstack_size;
} sqstack;

int Create_sqstack(sqstack *s)
{

s->base = (int *)malloc(sizeof(int)*sqstack_Initsize);
if(!(s->base))
exit(0);
s->top = s->base ;

s->sqstack_size = sqstack_Initsize;
return OK;
}

int Push(sqstack *s,int item)
{
if(s->top - s->base >=s->sqstack_size)
// exit(0);
{
printf("空间不够,须追加空间!\n");
s->base = (int *)realloc(s->base,(s->sqstack_size+sqstack_Increase_size)*sizeof(int));
if(!(s->base))
exit(0);
s->top = s->base+s->sqstack_size;
//*(s->top) = item;
s->sqstack_size = s->sqstack_size + sqstack_Increase_size;
}
*(s->top) = item;
s->top++;

return OK;
}

int Len_sqstack(sqstack *s)
{
return s->top - s->base;
}

int pop(sqstack *s)
{
while(s->top > s->base)
{
printf("%d\n",*(--s->top));
// s->top--;
}
return OK;
}

int Trease_sqstack(sqstack *s)
{
int *temp = s->base ;
while(temp < s->top)
{
printf("%d\n",*temp);
temp ++;
}
return OK;
}

 

 

int main()
{
sqstack s ; /* 此处应该定义一个栈,然后传入栈的地址 */

Create_sqstack(&s);

for(int i = 0;i<81;++i)
{
// Push(&s,1);
// Push(&s,2);
// Push(&s,3);
// Push(&s,4);
Push(&s,i);
}

// printf("%d\n\n\n\n\n\n",Len_sqstack(&s));

Trease_sqstack(&s);

// pop(&s);

// Trease_sqstack(&s);
return 0;

}

posted @ 2018-12-08 18:58  请叫我晓风哥哥  阅读(156)  评论(0编辑  收藏  举报