2025-12-08 14:00:19 +01:00

39 lines
883 B
C

#include <stdlib.h>
#include "stack.h"
// Pushes data onto the stack and returns new stack top
StackNode *push(StackNode *stack, void *data) {
StackNode *node = malloc(sizeof(StackNode));
if (!node) return stack; // allocation failed → leave stack unchanged
node->data = data;
node->next = stack;
return node; // new top
}
// Removes the top element, frees node (NOT data), returns new top
StackNode *pop(StackNode *stack) {
if (stack == NULL) return NULL;
StackNode *next = stack->next;
free(stack);
return next; // new top
}
// Returns data of top node or NULL
void *top(StackNode *stack) {
if (!stack) return NULL;
return stack->data;
}
// Frees entire stack (NOT data!)
void clearStack(StackNode *stack) {
while (stack != NULL) {
StackNode *next = stack->next;
free(stack);
stack = next;
}
}