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 | #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[]) {
Node* top = NULL; // empty stack
for(char ch = 'A'; ch <= 'Z'; ch++) { // RULE: Use character constant not int if poss.
stack_push(&top, ch);
}
print_stack(top);
stack_clear(&top); // will free the memory
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.