I am studying data structures and I have implemented a stack using a linked list.
stack.h
#ifndef STACK_H
#define STACK_H
#include <stdbool.h>
typedef char StackElement;
typedef struct stack_CDT *Stack;
Stack stack_init();
void stack_destroy(Stack s);
bool stack_is_empty(Stack s);
void stack_push(Stack s, StackElement elem);
StackElement stack_pop(Stack s);
#endif
stack.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "stack.h"
typedef struct node {
StackElement data;
struct node *next;
} Node;
Node *node_create(StackElement data)
{
Node *new = malloc(sizeof *new);
new->data = data;
new->next = NULL;
return new;
}
void node_insert(Node **node_ref, Node *new)
{
if (new == NULL)
return;
new->next = *node_ref;
*node_ref = new;
}
void node_delete(Node **node_ref)
{
if (*node_ref == NULL)
return;
Node *next = (*node_ref)->next;
free(*node_ref);
*node_ref = next;
}
void list_delete(Node **head_ref)
{
while ((*head_ref) != NULL)
node_delete(head_ref);
}
typedef struct stack_CDT {
Node *top;
} StackCDT;
StackCDT *stack_init()
{
StackCDT *new = malloc(sizeof *new);
new->top = NULL;
return new;
}
void stack_destroy(StackCDT *s)
{
list_delete(&(s->top));
free(s);
}
bool stack_is_empty(StackCDT *s)
{
return s->top == NULL;
}
void stack_push(StackCDT *s, StackElement elem)
{
Node *new = node_create(elem);
node_insert(&(s->top), new);
}
StackElement stack_pop(StackCDT *s)
{
if (stack_is_empty(s)) {
fprintf(stderr, "Can't pop element from stack, stack is empty.\n");
exit(1);
}
StackElement elem = s->top->data;
node_delete(&(s->top));
return elem;
}
stacktest.c
#include <stdio.h>
#include <string.h>
#include "stack.h"
#define MAX_STR_LEN 100
void stacktest()
{
printf("Enter a string(not more than %d characters): ", MAX_STR_LEN);
char input[MAX_STR_LEN + 1];
fgets(input, sizeof input, stdin);
char *pos;
if ((pos = strchr(input, '\n')) != NULL)
*pos = '\0';
Stack stack = stack_init();
for (char *c = input; *c; c++)
stack_push(stack, *c);
printf("Popped characters are: ");
while (!stack_is_empty(stack))
printf("%c", stack_pop(stack));
printf("\n");
stack_destroy(stack);
}
int main()
{
stacktest();
return 0;
}
Is my implementation all right?