[C language version] Implement stack using sequence table

    In data structures, stack is one of the most important concepts, but there is no corresponding data structure in C language. This is probably because the stack structure is too simple.

We can implement a stack through a sequence list or a linked list.

    In the stack, we have three basic operations: pushing, popping, and taking the top element of the stack . In addition, we should also initialize the stack (initialization is a very important habit in programming, don't program if you don't feel comfortable)

   

#include <stdio.h>
#include <stdlib.h>
#define 100 MAX;

typedef char StackType;
//extern StackType *data = (StackType*)malloc(sizeof(StackType));
typedef struct Stack{
        StackType* st;
        size_t size;
}Stack;
void StackInit(Stack* stack,StackType* base){//栈的初始化
    if (stack == NULL)
        return;
    stack->size = 0;
    stack->st = (StackType *)malloc((sizeof(StackType) * 100));
    base = stack->st;
    return;
}

    At the beginning, I thought of using extern to define a global variable, and then using malloc to open up a memory space. However, in the actual process, I found that defining the global variable externally would reduce the readability of the code. Let's forget about global variables when it comes to practical use. So in the end we define the sequence table in Init.

   Pushing and popping the stack, taking the top element of the stack:

Stack* StackDestroy(Stack* stack,StackType* base){//销毁
    if (stack == NULL)
        return NULL;
    stack->size = 0;
    free(base);
    return NULL;
};
Stack* StackPush(Stack* stack,StackType value,StackType* base){//入栈
    if (stack == NULL)
        return NULL;
    if (stack->size == MAX){
           realloc(base,MAX*2);
    }
    stack->size++;
    stack->st++;
    *(stack->st) = value;
    return stack;
};
Stack* StackPop(Stack* stack){//出栈
    if (stack == NULL)
        return NULL;
    stack->size--;
    stack->st--;
    return stack;
}
StackType* StackTop(Stack* stack){//取栈顶元素
    if (stack == NULL)
        return NULL;
    return stack->st;
}

Guess you like

Origin blog.csdn.net/xiagu_jinchengwu/article/details/79962874
Recommended