Double/stack.c
2025-11-27 15:27:58 +01:00

39 lines
938 B
C

#include <stdlib.h>
#include "stack.h"
// Pushes data as pointer onto the stack.
StackNode *push(StackNode *stack, void *data)
{
StackNode *node = (StackNode*)malloc(sizeof(StackNode));
if (node == NULL) return stack; // allocation failed, return unchanged stack
node->data = data;
node->next = stack;
return node;
}
// Deletes the top element of the stack (latest added element) and releases its memory. (Pointer to data has to be
// freed by caller.)
StackNode *pop(StackNode *stack)
{
if (stack == NULL) return NULL;
StackNode *next = stack->next;
free(stack);
return next;
}
// Returns the data of the top element.
void *top(StackNode *stack)
{
return (stack != NULL) ? stack->data : NULL;
}
// Clears stack and releases all memory.
void clearStack(StackNode *stack)
{
while (stack != NULL)
{
StackNode *next = stack->next;
free(stack);
stack = next;
}
}