一、定义
typedef struct StackElement_t_{ void *data; struct StackElement_t *next; } StackElement_t; typedef struct Stack_t_ { int size; int capacity; int (*destory)(void *data); StackElement_t *head; } Stack_t;
typedef struct StackElement_t_{
void *data;
struct StackElement_t *next;
} StackElement_t;
typedef struct Stack_t_ {
int size;
int capacity;
int (*destory)(void *data);
StackElement_t *head;
} Stack_t;
二、初始化:
int stack_init( Stack_t *st, int maxsize, int( *destory)(void *data)){ st->size = 0; st->capacity = maxsize; st->destory = destory; st->head = NULL; return 0; }
int stack_init( Stack_t *st, int maxsize, int( *destory)(void *data)){
st->size = 0;
st->capacity = maxsize;
st->destory = destory;
st->head = NULL;
return 0;
}
三、入栈
int stack_push( Stack_t *st, const void *data){ if( stack_is_full( st) ) return OVERFLOW_ERROR; StackElement_t *new_element = NULL; new_element->data = data; new_element->next = st->head; st->head = st->head->next; st->size++; return 0; }
int stack_push( Stack_t *st, const void *data){
if( stack_is_full( st) )
return OVERFLOW_ERROR;
StackElement_t *new_element = NULL;
new_element->data = data;
new_element->next = st->head;
st->head = st->head->next;
st->size++;
return 0;
}
四、出栈
int stack_pop( Stack_t *st){ if( stack_is_empty( st ) ) return -1; void *data = stack_top( st ); StackElement_t *del_element = st->head; st->destroy( data ); free( del_element); del_element = NULL; st->size--; return 0; }
int stack_pop( Stack_t *st){
if( stack_is_empty( st ) )
return -1;
void *data = stack_top( st );
StackElement_t *del_element = st->head;
st->destroy( data );
free( del_element);
del_element = NULL;
st->size--;
return 0;
}
五、栈顶元素
void *stack_top( Stack_t *st){ if( stack_is_empty( st )) return NULL; return st->head->data; }
void *stack_top( Stack_t *st){
if( stack_is_empty( st ))
return NULL;
return st->head->data;
}
六、销毁栈
int stack_destroy( Stack_t *st){ while( st->size > 0){ stack_pop( st ); } return 0; }
int stack_destroy( Stack_t *st){
while( st->size > 0){
stack_pop( st );
}
return 0;
}
七、其他
(1)判断栈是否为空
int stack_is_empty( Stack_t *st) { return (st->size == 0 ); }
int stack_is_empty( Stack_t *st)
{
return (st->size == 0 );
}
(2)判断栈是否满
int stack_is_full( Stack_t *st ) { return (st->size = st->capacity); }
int stack_is_full( Stack_t *st )
{
return (st->size = st->capacity);
}
(3)返回栈的实际长度
int stack_size( Stack_t *st) { return st->size; }
int stack_size( Stack_t *st)
{
return st->size;
}
(4)返回栈的容量
int stack_capacity( Stack_t *st) { return st->capacity; }
int stack_capacity( Stack_t *st)
{
return st->capacity;
}