链式栈实现

#include <stdlib.h>
#include <assert.h>

typedef void* element_t;

struct stack_node_t {
        element_t data;
        struct stack_node_t* prev;      // 指向前一个元素,方向是向栈底
};

struct stack_t {
        struct stack_node_t* base;
        struct stack_node_t* top;
        int size;
};

int stack_init(struct stack_t* s) {
        assert(NULL != s);

        s->base = NULL;
        s->top  = NULL;
        s->size = 0;
        return 0;
}

struct stack_t* stack_create(void) {
        struct stack_t* s = (struct stack_t *)malloc(sizeof(*s));
        if (!s) {
                printf("memory allocated error");
                return NULL;
        }

        stack_init(s);
        return s;
}

int stack_push(struct stack_t* s, element_t data) {
        struct stack_node_t* node = NULL;
        
        assert(NULL != s);

        node = (struct stack_node_t *)malloc(sizeof(*node));
        if (!node) {
                printf("memory allocated error");
                return -1;
        }

        node->data = data;
        if (!s->base)
                s->base = node;

        node->prev = s->top;
        s->top = node;
        s->size++;
        return 0;
}

int stack_pop(struct stack_t* s, element_t* data) {
        struct stack_node_t* tmp = NULL;

        assert(NULL != s);
        assert(NULL != data);

        tmp = s->top;
        if (!tmp)
                return -1;

        *data = tmp->data;
        s->top = tmp->prev;
        free(tmp);
        s->size--;
        return 0;
}

int stack_is_empty(struct stack_t* s) {
        assert(NULL != s);

        if (s->size)
                return 0;
        else
                return 1;
}

还有一种更简单的实现,没有使用单独的类型表示栈对象,但是会给某些操作带来额外的开销,比如检查栈的元素个数,或者直接访问栈底等等,

/*
 *      链式栈的实现
 *      NULL <- base <- ... <- top
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef void* element_t;

struct stack_node_t {
        element_t data;
        struct stack_node_t* prev;
};

void stack_init(struct stack_node_t** s) {
        assert(NULL != s);
        *s = NULL;
}

int stack_push(struct stack_node_t** s, element_t data) {
        struct stack_node_t* s_node;

        assert(NULL != s);

        s_node = (struct stack_node_t *)malloc(sizeof(*s_node));
        if (!s_node) {
                printf("memory allocated error");
                return -1;
        }

        s_node->data = data;
        s_node->prev = *s;
        *s = s_node;
        return 0;
}

int stack_pop(struct stack_node_t** s, element_t* data) {
        struct stack_node_t* tmp;
        
        assert(NULL != s);

        tmp = (*s);
        if (!tmp)
                return -1;
        *data = tmp->data;
        *s = tmp->prev;
        free(tmp);
        return 0;
}
posted @ 2013-08-25 23:07  WendellYih  阅读(277)  评论(0编辑  收藏  举报