golang
package stack import ( "errors" ) type Stack []interface{} func(stack *Stack) Push(v interface{}) { *stack = append(*stack, v) } func(stack *Stack) Pop() (interface{}, error){ if len(*stack) == 0 { return nil, errors.New("stack empty") } v := (*stack)[len(*stack) - 1] *stack = (*stack)[:len(*stack) - 1] return v, nil } func(stack *Stack) Top() (interface{}, error) { if len(*stack) == 0 { return nil, errors.New("stack empty") } return (*stack)[len(*stack) - 1], nil } func(stack *Stack) Len() int { return len(*stack) }
同样的思路用c实现:
typedef struct my_stack_t my_stack_t; struct my_stack_t { void **s; /* 元素为void *的数组 */ int use; /* 已存入的元素个数 */ int size; /* 在内存中已分配的个数 */ void (*do_free)(void *); }; #define DEFAULT_N 100 int stack_init(my_stack_t *s, void (*do_free)()) { assert(s != NULL); s->s = (void **)malloc(sizeof(void *) * DEFAULT_N); s->use = 0; s->size = DEFAULT_N; s->do_free = do_free; return 0; } int stack_push(my_stack_t *s, void *v) { assert(s != NULL); char *p; if (s->use == s->size) { p = realloc(s->s, s->size * 2); if (p == NULL) return -1; s->size *= 2; } s->s[s->use++] = v; return 0; } void *stack_pop(my_stack_t *s) { assert(s != NULL); if (s->use == 0) { return NULL; } return s->s[--s->use]; } void *stack_top(my_stack_t *s) { assert(s != NULL); if (s->use == 0) { return NULL; } return s->s[s->use - 1]; } int stack_len(my_stack_t *s) { return s->use; } int stack_free(my_stack_t *s) { void *v; if (s->do_free == NULL) { return 0; } while ((v = stack_pop(s)) != NULL) { s->do_free(s); } return 0; }
*golang里的interface{} 等同于c里的void *
有疑问加站长微信联系(非本文作者)