顺序栈的实现(C语言)

来源:互联网 发布:c语言获取数组的长度 编辑:程序博客网 时间:2024/05/01 05:16
/*顺序栈VS2010 调试*/#include <stdio.h>#include <malloc.h>#include <stdlib.h>#define TRUE 1#define FALSE 0#define STACK_INIT_SIZE 100#define STACKINCREASEMENT 10struct SeqStack{int *elem;int top;int MAXNUM;};//初始化栈int init_seq_stack(struct SeqStack *L){L->elem = (int *)malloc(STACK_INIT_SIZE * sizeof(int));if (!L->elem){return 0;}L->top = 0;L->MAXNUM = STACK_INIT_SIZE;return 1;}/*函数功能:判断是否栈满返 回 值:0 栈满; 1 栈未满*/int is_stack_full(struct SeqStack L){return (L.top == L.MAXNUM);}/*函数功能:判断是否栈空返 回 值:0 栈空; 1 栈未空*/int is_stack_empty(struct SeqStack L){if (L.top == 0){return 0;}else{return 1;}}/*函数功能:数num 进栈返 回 值:0 进栈失败; 1 进栈成功*/int push_stack(struct SeqStack *L, int num){if (is_stack_full(*L)){return 0;}L->top++;L->elem[L->top] = num;return 1;}/*函数功能:出栈,出栈的数存到x内返 回 值:0 失败; 1 成功*/int pop_stack(struct SeqStack *L, int *x){if (!is_stack_empty(*L)){return 0;}*x = L->elem[L->top];L->top = L->top - 1;return 1;}/*函数功能:取栈顶元素返 回 值:栈顶元素值*/int get_top_elem(struct SeqStack L){return L.elem[L.top];}/*函数功能:打印栈内元素*/void print_stack_elem(struct SeqStack L){int i = 0;printf("TOP\n");for(i = L.top; i > 0; i--){printf("%d\n", L.elem[i]);}printf("BOTTOM\n");printf("\n");}/*函数功能:将栈置空*/void set_empty(struct SeqStack *L){L->top = 0;}/*函数功能:销毁栈*/int destory_stack(struct SeqStack *L){if (!L->elem){return 0;}free(L->elem);return 1;} int main(int argc, char *argv[]){int x = 0;struct SeqStack L;init_seq_stack(&L);push_stack(&L, 7);push_stack(&L, 4);push_stack(&L, 5);push_stack(&L, 8);push_stack(&L, 9);print_stack_elem(L);pop_stack(&L, &x);print_stack_elem(L);destory_stack(&L);return 0;}

原创粉丝点击