数据结构之栈(二)

来源:互联网 发布:淘宝不支持子账号登陆 编辑:程序博客网 时间:2024/06/03 19:18

栈      先进后出


定义节点结构体,包含双向链表

struct node_t {    int data;    struct list_head list;};

申明栈:

struct stack_t{    struct list_head head;    int (*is_empty)(struct stack_t *);                              //判断栈是否为空    struct node_t *(*push)(struct stack_t *, int data);             //进栈    int (*pop)(struct stack_t *);                                   //出栈    int (*top)(struct stack_t *);                                   //返回栈顶元素};struct stack_t *stack_init();                                       //初始化栈void stack_destory(struct stack_t *);                               //销毁栈
具体实现:

进栈:

struct node_t *stack_push(struct stack_t *stack, int data){    struct node_t *node = (struct node_t *)malloc(sizeof(struct node_t));    INIT_LIST_HEAD(&node->list);    node->data = data;    list_add(&node->list, &stack->head);    return node;}
出栈:

int stack_pop(struct stack_t *stack){    struct node_t *node = container_of(stack->head.next, struct node_t, list);    int data = node->data;    list_del(&node->list);    free(node);    return data;}
返回栈顶元素:

int  stack_top(struct stack_t *stack){    struct node_t *node = container_of(stack->head.next, struct node_t, list);    int data = node->data;    return data;}

初始化栈:

struct stack_t *stack_init(){    struct stack_t *stack = (struct stack_t *)malloc(sizeof(struct stack_t));    INIT_LIST_HEAD(&stack->head);    stack->is_empty = stack_is_empty;    stack->push = stack_push;    stack->pop = stack_pop;    stack->top = stack_top;    return stack;}
销毁栈:

void stack_destory(struct stack_t *stack){    struct node_t *node = NULL;    struct node_t *tmp = NULL;    list_for_each_entry_safe(node, tmp, &stack->head, list)    {        list_del(&node->list);        free(node);    }}
















参考 数据结构(C语言版) 

0 0
原创粉丝点击