本文共 1936 字,大约阅读时间需要 6 分钟。
stack.h
#ifndef __STACK_H__#define __STACK_H__#include#include #include #include #ifdef __cplusplusextern "C"{#endifstruct validator{ bool (*const vali) (struct validator *p_this,int value); void *const p_data;}validator;struct range{ int min; int max;}range;struct { int previous_value;}previous;struct stack{ int top; const size_t size; struct validator * const p_validator; int *p_buf;}stack;#ifdef __cplusplus}#endif#endif
stack.c
#include "stack.h"static int stack_empty(struct stack *p_this){ return p_this->top == 0;}static int stack_full(struct stack *p_this){ return p_this->top == p_this->size;}static int validate_range(struct validator *p_this,int value){ if(!p_this) return -1; struct range *temp = (struct range *) p_this->p_data; return (temp->min < value && temp->max > value);}int validate(struct validator *p_this,int value){ if(!p_this) return 0; return p_this->vali(p_this,value);}int pop(struct stack *p_this,int *value){ if(!p_this || stack_empty(p_this)) return -1; p_this->top--; *value = p_this->p_buf[p_this->top]; return 0;}int push(struct stack *p_this,int value){ if(stack_full(p_this) || !validate(p_this->p_validator,value)) return -1; p_this->p_buf[p_this->top] = value; p_this->top++; return 0;}int main(int argc,char *argv[]){ int buff[16]; struct range a = { .min = 10, .max = 100 }; struct validator b = { .p_data = (void *)&a, .vali = validate_range, }; struct stack c = { .top = 0, .size = 16, .p_validator = &b, .p_buf = buff, }; push(&c,12); int d; pop(&c,&d); printf("%d\n",d); return 0;}
Makefile
src=stack.cobj=$(src:.o=.c)target=stackall:$(target)$(target):$(obj) gcc $(obj) -o $@ -std=c99%.o : %.c gcc -c $< -O $@ -std=c99clean: rm -af $(target) $(obj)
转载地址:http://euftb.baihongyu.com/