栈:定义-一种以先入后出为存储数据方式的数据结构
实现:
stack.h文件
#include <stdbool.h>
extern void push(char);
extern char pop();
extern bool is_empty();
extern bool is_ful();
extern void init_stack(int);
extern void destroy();
stack.c文件
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
static int top = 0;
static char *stack;
static int size = 512;
static int sz;
bool is_empty()
{
return top == 0;
}
bool is_full()
{
return top == sz;
}
void init_stack(int num)
{
if(num <= 0)
sz = size;
else
sz = num;
stack = malloc(sz);
}
void push(char input)
{
if(is_full())
{
printf("sz=%d---------\n",sz);
stack = realloc(stack, sz*2);
sz = sz * 2;
}
stack[top] = input;
top++;
}
char pop()
{
return stack[--top];
}
void destroy()
{
free(stack);
}
test.c文件
#include <stdio.h>
#include "stack.h"
int main()
{
char *str = "abcdefghigk";
init_stack(3);
while(*str != '\0')
{
push(*str);
str++;
}
while(is_empty() == 0)
{
putchar(pop());
}
destroy();
putchar('\n');
return 0;
}