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
#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) { .next = NULL, .ch = ch };  // Compound literal
    if(*a_top != NULL) {  // If stack is not initially empty...
        new_top -> next = *a_top;   // make the new top refer to the existing top
    }
    *a_top = new_top; // new top becomes the top of the stack
    assert(*a_top != NULL);  // Just added something, so can't possibly be empty now.
    assert((*a_top) -> ch == ch);  // Top should have the character we just pushed.
}

char stack_pop(Node** a_top) {  // Usage:  Must not be called with an empty stack.
    Node* old_top = *a_top;
    char ch = old_top -> ch;
    *a_top = old_top -> next;
    free(old_top);
    return ch;
}

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

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

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

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

    printf("- clear stack one element at a time\n");
    while(!stack_is_empty(top)) {
        print_stack(top);
        char ch = stack_pop(&top);
        printf(" - removed '%c'\n", ch);
    }
    print_stack(top);
    
    printf("\n-----------\n");
    printf("Make a new stack\n");
    stack_push(&top, 'W');
    stack_push(&top, 'X');
    stack_push(&top, 'Y');
    stack_push(&top, 'Z');
    // 
    print_stack(top);
    printf("- clear stack with stack_clear(…)\n");
    stack_clear(&top);
    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.