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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

typedef struct _Node {
    char ch;
    struct _Node* next;
} Node;

void stack_push(Node** a_top, char ch) {
    Node* new_top = malloc(sizeof(*new_top));  // NO (Node)malloc(…)!  NO sizeof(Node)!
    *new_top = (Node) { .ch = ch, .next = NULL };  // Compound literal
    if(*a_top != NULL) {  // if the stack is NOT intially empty
        new_top -> next = *a_top;  // make the new top refer to the old top
    }
    *a_top = new_top;
    assert(*a_top != NULL);  // just added a node so cannot possibly be empty now.
    assert((*a_top) -> ch == ch);  // top must have the char that was just added.
}

void print_stack(Node* top) {
    printf("TOP: ");
    for(Node* curr = top; curr != NULL; curr = curr -> next) {
        printf("['%c'] → ", curr -> ch);
    }
    printf("NULL\n");
}

char stack_pop(Node** a_top) {
    Node* old_top = *a_top;
    char ch = old_top -> ch;  // extract the character
    *a_top = old_top -> next;
    free(old_top);
    return ch;
}

void stack_clear(Node** a_top) {
    while(*a_top != NULL) {
        stack_pop(a_top);
    }
}

bool stack_is_empty(Node* top) {
    return top == NULL;
}

int main(int argc, char* argv[]) {
    printf("___________________\n");
    printf("Create a stack\n");
    Node* top = NULL;  // empty stack
    stack_push(&top, 'A');
    assert(top != NULL && top -> ch == 'A');
    stack_push(&top, 'B');
    stack_push(&top, 'C');
    stack_push(&top, 'D');
    print_stack(top);

    printf("___________________\n");
    printf("Empty a stack one element at a time using stack_pop(…)\n");
    while(top != NULL) {
        char ch = stack_pop(&top);
        printf("- removed '%c'\n", ch);
    }
    assert(stack_is_empty(top));  // must be empty now

    printf("___________________\n");
    printf("Repopulate stack again\n");
    stack_push(&top, 'W');
    stack_push(&top, 'X');
    stack_push(&top, 'Y');
    stack_push(&top, 'Z');
    print_stack(top);

    printf("___________________\n");
    printf("Empty a stack all at once using stack_clear(…)\n");
    stack_clear(&top);
    assert(stack_is_empty(top));  // must be empty now
    print_stack(top);

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2023 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.