使用数组实现简单的入栈出栈 - 顺序栈
使用线性表的链式存储结构实现 - 链栈

顺序栈的实现

实现代码

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

typedef int STACKTYPE;

struct StackSpace {
    int size;
    STACKTYPE* space;
    int ip;
};
typedef struct StackSpace Stack;



Stack* createStack(int size) {
    STACKTYPE* space = malloc(sizeof(STACKTYPE) * size);
    struct StackSpace* stack = malloc(sizeof(Stack));
    if (space == NULL || stack == NULL) perror("create stack fail");
    stack->space = space;
    stack->ip = -1;
    stack->size = size;
    return stack;
}

void destroyStack(Stack* stack) {
    free(stack->space); // Free stack space
    free(stack); // Release the entire stack structure
}

void pushStack(Stack* stack,STACKTYPE value) {
    if (stack->ip >= stack->size) perror("the maximum stack space is exceeded");
    stack->space[++stack->ip] = value;
}

STACKTYPE popStack(Stack* stack) {
    if (stack->ip < 0) perror("reach the bottom of the stack");
    return stack->space[stack->ip--];
}


int main() {
    Stack* stack = createStack(100);

    for (int i = 0; i < 100; ++i) {
        pushStack(stack, i);
    }
    for (int i = 0; i < 100; ++i) {
        printf("pop [%d]: %d\n", i, popStack(stack));
    }
    destroyStack(stack);
}

链栈的实现

实现代码

List.h

//
// Created by Mason on 2021-08-09.
//


#ifndef C90_LIST_H
#define C90_LIST_H

typedef int ListType; // type

typedef struct Node List;




struct Node {
    ListType elem;
    List* nextNode;
};

#endif //C90_LIST_H

main.c

#include "List.h"

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


List* createStack() {
    List* stack = malloc(sizeof(List));
    stack->nextNode = NULL;
    stack->elem = -1;
    return stack;
}

void destroyStack(List* stack) {
    free(stack);
}

void pushStack(List** stack, ListType value) {
    List* ps =  malloc(sizeof(List));
    ps->elem = value;
    ps->nextNode = *stack;
    *stack = ps;

}

ListType popStack(List** stack) {
    if ((*stack)->nextNode == NULL) perror("end of stack buttom");
    ListType t = (*stack)->elem;
    *stack = (*stack)->nextNode;
    return t;
}

int main() {

    List* stack = createStack();
    for (int i = 0; i < 100; ++i) {
        pushStack(&stack, i);
    }

    for (int i = 0; i < 100; ++i) {
        printf("stack [%d]: %d\n", i, popStack(&stack));
    }

    destroyStack(stack);
}