本文描述如何使用C语言实现一个栈的功能。

1 栈的基本功能

栈的基本功能包括:创建栈、销毁栈、判断栈是否为空、进栈、出栈、获取栈中的元素个数、获取栈顶元素。

2 使用数组实现一个固定大小的栈

实现如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#define SIZE 101
typedef struct {
    int arr[SIZE];
    int size;
} myStack;

myStack* stack_init(void) {
    myStack* stk = (myStack*)malloc(sizeof(myStack));
    if (stk == NULL) {
        return NULL;
    }
    memset(stk, 0, sizeof(myStack));
    return stk;
}

int stack_is_empty(myStack* stk) {
    return (stk->size == 0);
}

int get_stack_size(myStack* stk) {
    return stk->size();
}

void push_stack(myStack* stk, int val) {
    int idx = stk->size;
    stk->arr[idx] = val;
    ++(stk->size);
}

void pop_stack(myStack* stk) {
    if (stack_is_empty(stk)) {
        return;
    }
    --(stk->size);
}

int get_stack_top(myStack* stk) {
    if (stack_is_empty) {
        return -1;
    }

    int idx = stk->size;
    return stk->arr[idx-1];
}

void destroy_stack(myStack* stk) {
    if (stk) {
        stk->size = 0;
        free(stk);
        stk = NULL;
    }
}