顺序栈操作接口函数声明
void stack_init(stack_t *st);
int empty(stack_t *st);
int stack_size(stack_t *st);
datatype read(stack_t *st);
void push(stack_t *st,datatype dat);
datatype pop(stack_t *st);
顺序栈数据结构声明
#define STACK_SIZE 100
typedef int datatype;
typedef struct stack
{
datatype buf[STACK_SIZE];
int top;
}stack_t;
完整代码
#include "stdio.h"
#define STACK_SIZE 100
typedef int datatype;
typedef struct stack
{
datatype buf[STACK_SIZE];
int top;
}stack_t;
void stack_init(stack_t *st);
int empty(stack_t *st);
int stack_size(stack_t *st);
datatype read(stack_t *st);
void push(stack_t *st,datatype dat);
datatype pop(stack_t *st);
void stack_init(stack_t *st)
{
memset(&st->buf,0,STACK_SIZE);
st->top = 0;
}
int empty(stack_t *st)
{
return (st->top)?(0):(1);
}
int stack_size(stack_t *st)
{
return st->top;
}
datatype read(stack_t *st)
{
int i = 0;
if(empty(st))
{
printf("stack emptt ,exit");
return -1;
}
printf("----- stack data -----\n");
for(i = 0;i < st->top;i++)
{
printf("%d : [%d] \n",i,st->buf[i]);
}
return 1;
}
void push(stack_t *st,datatype dat)
{
if(st->top < STACK_SIZE)
{
st->buf[st->top++] = dat;
}
else
{
printf("stack full ,exit");
}
}
datatype pop(stack_t *st)
{
if(empty(st))
{
printf("stack empty ,exit");
return -1;
}
return st->buf[--st->top];
}
int main(void)
{
stack_t sq_stack;
stack_init(&sq_stack);
printf("push some data int the sequence stack\n");
push(&sq_stack,1);
push(&sq_stack,2);
push(&sq_stack,3);
push(&sq_stack,4);
push(&sq_stack,5);
push(&sq_stack,6);
push(&sq_stack,7);
push(&sq_stack,8);
printf("stat size : %d \n",stack_size(&sq_stack));
read(&sq_stack);
printf("pop data is : %d\n",pop(&sq_stack));
printf("pop data is : %d\n",pop(&sq_stack));
printf("pop data is : %d\n",pop(&sq_stack));
read(&sq_stack);
push(&sq_stack,77);
push(&sq_stack,99);
read(&sq_stack);
return;
}
运行测试结果