栈(Stack)的C语言实现

栈(Stack)实现的是一个后进先出策略。元素弹出的顺序正好和它们压入的次序相反。S.top表示栈顶元素,S.size表示栈的大小。如果试图对一个S.top=0的栈进行弹出操作,则称栈下溢。如果S.top超过了S.size,则称栈上溢。
这里使用动态分配内存的方式实现栈,并可以动态的调整栈的大小,如有错误敬请指正。

//Item.h
typedef struct ITEM {
    int key;
    void * statellite;
} item_t;
//Stack.h
#ifndef STDIO_H
#define STDIO_H
#include <stdio.h>
#endif

#ifndef STDLIB_H
#define STDLIB_H
#include <stdlib.h>
#endif

#ifndef ITEM_H
#define ITEM_H
#include "Item.h"
#endif

typedef struct STACK
{
    int top;
    int size;
    item_t* array;
} stack_t;

int stack_init(stack_t * S, int size);
int stack_resize(stack_t * S, int size);
int stack_free(stack_t * S);
int stack_empty(stack_t * S);
int stack_push(stack_t * S, item_t item);
int stack_pop(stack_t * S, item_t *item);
void stack_info(stack_t * S);
//Stack.c
#include "Stack.h"

int stack_init(stack_t * S, int size) {
    S->top = 0;
    S->array = (item_t*)calloc(size, sizeof(item_t));
    if (S->array != NULL) {
        S->size = size;
        return 1;
    } else {
        S->size = 0;
        fprintf(stderr, "Stack init fail.\n");
        return 0;
    }
}
int stack_resize(stack_t * S, int size) {
    S->array = (item_t*)realloc(S->array, size * sizeof(item_t));
    if (S->array != NULL) {
        S->size = size;
        if (S->top > S->size) {
            S->top = S->size;
        }
        return 1;
    } else {
        S->top = 0;
        S->size = 0;
        fprintf(stderr, "Stack resize fail.\n");
        return 0;
    }
}
int stack_free(stack_t * S) {
    free(S->array);
    S->array = NULL;
    S->top = 0;
    S->size = 0;
    return 1;
}
int stack_empty(stack_t * S) {
    if (S->array == NULL) {
        fprintf(stderr, "Stack is not initialized.\n");
        return 1;
    }
    if (S->top == 0)
        return 1;
    else
        return 0;
}
int stack_push(stack_t * S, item_t item) {
    if (S->array == NULL) {
        fprintf(stderr, "Stack is not initialized.\n");
        return 0;
    }
    if (S->top < S->size) {
        S->array[S->top++] = item;
        return 1;
    } else {
        fprintf(stderr, "Stack overflow.\n");
        return 0;
    }
}
int stack_pop(stack_t * S, item_t * item) {
    if (S->array == NULL) {
        fprintf(stderr, "Stack is not initialized.\n");
        return 0;
    }
    if (!stack_empty(S)) {
        *item = S->array[--S->top];
        return 1;
    } else {
        fprintf(stderr, "Stack underflow\n");
        return 0;
    }
}
void stack_info(stack_t * S) {
    static int count = 0;
    printf("%d:\n", count++);
    if (S->array == NULL) {
        printf("stack is not initialized.\n-------------------------------\n");
        return;
    }
    printf("stack top:%d\n", S->top);
    printf("stack size:%d\n", S->size);
    printf("stack element:\n");
    for (int i = S->top - 1; i >= 0; i--) {
        printf("%d ", S->array[i].key);
    }
    printf("\n-------------------------------\n");
}

猜你喜欢

转载自blog.csdn.net/sinat_16709955/article/details/77387933