C语言实现简单的—栈
1,源码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>#define STACK_SIZE 10typedef struct stack{int data[STACK_SIZE];int top;
}SStack;SStack * CreateStack()
{return (SStack *)calloc(1, sizeof(SStack));
}int init_stack(SStack *st)
{if(!st) {printf("%s: stack is failed.\n", __FUNCTION__);return -1;}st->top = -1;//置为-1表示栈底memset( st->data, 0, sizeof(st->data));return 0;
}int StackFull(SStack *st)
{return st->top == (STACK_SIZE - 1);
}int StackEmpty(SStack *st)
{return st->top == (-1);
}int push_stack(SStack *st, int dat)
{if(!StackFull(st)){st->top++;st->data[st->top] = dat;return 0;}else {printf("%s: stack is full.\n", __FUNCTION__);return -1;}}int pop_stack(SStack *st, int *dat)
{if(StackEmpty(st)){printf("%s: stack is empty.\n", __FUNCTION__);return -1;}else{*dat = st->data[st->top];st->top--;return 0;}}int main()
{int i = 0;int dat = 0;SStack * pstack = (SStack *)CreateStack();init_stack(pstack);for(i =0 ; i<12; i++){push_stack(pstack, i);}i =0;printf("-1-->top: %d\n", pstack->top);while(!pop_stack(pstack, &dat)){printf("index: %d, dat: %d\n", i, dat);i++;usleep(1000);//出现错误时,防止cpu跑s}printf("-2-->top: %d\n", pstack->top);
}
2,总结
① 这里实现的是用数组实现的栈,栈的初始化需要将top = -1;
② 入栈操作需要判断full (top == max -1),出栈操作需要判断NULL (top == -1)
③ 方便后续查看