实现都放在.h文件中。
实现代码
#ifndef HO_STACK_H
#define HO_STACK_H
#include
#undef offsetof
struct stack_head {
struct stack_node *first;
};
struct stack_node {
struct stack_node *next;
};
#define STACK_HEAD_INIT {.first = NULL}
#define INIT_STACK_HEAD(ptr) ((ptr)->first = NULL)
#define offsetof(type, member) ((size_t)&((type *)0)->member)
#define stack_entry(ptr, type, member) (type *)((char *)ptr - offsetof(type, member))
static inline void stack_push(struct stack_node *n, struct stack_head *h) {
n->next = h->first;
h->first = n;
}
static inline struct stack_node *stack_pop(struct stack_head *h) {
struct stack_node *t;
t = h->first;
h->first = h->first ? h->first->next : NULL;
return t;
}
static inline struct stack_node *stack_top(struct stack_head *h) {
return h->first;
}
static inline int stack_empty(struct stack_head *h) {
return !h->first;
}
#define stack_for_each(pos, head) \
for(pos = (head)->first; pos; pos = pos->next)
#endif
2.如何使用
#include
#include
#include
#include "stack.h"
struct stack_node2 {
void *data;
struct stack_node stack;
};
int main() {
struct stack_head head = STACK_HEAD_INIT;
struct stack_node2 *tmp, *pos2;
struct stack_node *pos;
tmp = malloc(sizeof(struct stack_node2));
tmp->data = strdup("11111111");
stack_push(&(tmp->stack), &head);
tmp = malloc(sizeof(struct stack_node2));
tmp->data = strdup("22222222");
stack_push(&(tmp->stack), &head);
tmp = malloc(sizeof(struct stack_node2));
tmp->data = strdup("33333333");
stack_push(&(tmp->stack), &head);
#if 0
stack_for_each(pos, &head) {
pos2 = stack_entry(pos, struct stack_node2, stack);
printf("==========%p:%s\n", pos2, (char *)pos2->data);
}
#endif
/*test stack_top*/
pos = stack_top(&head);
pos2 = stack_entry(pos, struct stack_node2, stack);
printf("%s\n", (char *)pos2->data);
while (!stack_empty(&head)) {
pos = stack_pop(&head);
pos2 = stack_entry(pos, struct stack_node2, stack);
printf("%s\n", (char *)pos2->data);
free(pos2->data);
free(pos2);
}
return 0;
}