C基础--栈的静态和动态生成
main.c 文件
#include <stdio.h> #include "stack.h" int main(void) { char *str = "abcdefghijklmn"; init_stack(3); //创建动态栈 while (*str != '\0') { push(*str); str++; } while (is_empty() == 0) putchar(pop()); putchar('\n'); destory_stack(); //销毁动态栈 return 0; }
stack.c文件
#include <stdio.h> #include <stdlib.h> /* static char stack[512] = {0}; //数据栈 static int top = 0; //栈指针 void push(char ch) { stack[top++] = ch; } char pop(void) { return stack[--top]; } int is_empty(void) { return top == 0; } int is_full(void) { return top == 512; } */ static int sz = 512; static char *stack; //数据栈 static int top = 0; //栈指针 void init_stack(int size) { if (size == 0) size = sz; else sz = size; stack = (char *)malloc(sz); } void destory_stack(void) { free(stack); } void push(char ch) { if (top == sz) { sz += sz; stack = realloc(stack, sz); } stack[top++] = ch; } char pop(void) { return stack[--top]; } int is_empty(void) { return top == 0; } int is_full(void) { return top == sz; }
stack.h文件
extern void push(char ch); extern char pop(void); extern int is_empty(void); extern int is_full(void); extern void init_stack(int size); extern void destory_stack(void);