stack completed

This commit is contained in:
Jonas Urban 2025-11-21 00:32:57 +01:00
parent 12742b46fe
commit b0826ec057
2 changed files with 28 additions and 0 deletions

View File

@ -10,24 +10,47 @@
// Pushes data as pointer onto the stack.
StackNode *push(StackNode *stack, void *data)
{
StackNode *newNode = malloc(sizeof(StackNode));
if (!newNode)
return stack;
newNode->data = data;
newNode->next = stack;
return newNode;
}
// 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 *newTopElement = stack->next;
free(stack);
return newTopElement;
}
// Returns the data of the top element.
void *top(StackNode *stack)
{
if (!stack)
return NULL;
return stack->data;
}
// Clears stack and releases all memory.
void clearStack(StackNode *stack)
{
StackNode *current = stack;
while (current)
{
StackNode *next = current->next;
free(current);
current = next;
}
}

View File

@ -8,6 +8,11 @@ The latest element is taken from the stack. */
#include <stdlib.h>
//TODO: passenden Datentyp als struct anlegen
typedef struct stack
{
void *data;
struct stack *next;
} StackNode;
// Pushes data as pointer onto the stack.
StackNode *push(StackNode *stack, void *data);