1. Stack.h

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

typedef struct Stack {
    int* arr;
    int capacity;
    int top;
} Stack;

void StackInit(Stack* ps);

void StackDestroy(Stack* ps);

void CheckCap(Stack* ps);

void StackPush(Stack* ps, int data);

void StackPop(Stack* ps);

int StackTop(Stack* ps);

int StackEmpty(Stack* ps);

int StackSize(Stack* ps);

2. Stack.c

#include "Stack.h"

void StackInit(Stack* ps) {
    assert(ps);

    int* tmp = (int *)malloc(sizeof(int) * 10);
    if (tmp == NULL) {
        assert(0);
    }

    ps->arr = tmp;
    ps->capacity = 10;
    ps->top = 0;
}

void StackDestroy(Stack* ps) {
    assert(ps);

    free(ps->arr);
    ps = NULL;
}

void CheckCap(Stack* ps) {
    assert(ps);

    if (ps->capacity == ps->top) {  // full
        int* tmp = (int *)realloc(ps->arr, ps->capacity * 2);
        assert(tmp);

        ps->arr = tmp;
        ps->capacity *= 2;
    }
}

void StackPush(Stack* ps, int data) {
    assert(ps);

    CheckCap(ps);

    ps->arr[ps->top++] = data;
}

void StackPop(Stack* ps) {
    assert(ps);

    if (ps->top != 0) {
        ps->top--;
    }
}

int StackTop(Stack* ps) {
    assert(ps);
    assert(ps->top);

    return ps->arr[ps->top - 1];
}

int StackEmpty(Stack* ps) {
    assert(ps);

    return ps->top == 0;
}

int StackSize(Stack* ps) {
    assert(ps);

    return ps->top;
}
Last modification:September 8th, 2019 at 08:15 pm