Stack.h und stack.c programmiert

This commit is contained in:
Sven Hofmann 2025-12-11 15:55:04 +01:00
parent 4741345749
commit 4a386814a0
2 changed files with 51 additions and 4 deletions

51
stack.c
View File

@ -7,27 +7,70 @@
* `top`: liefert das oberste Element zurück,
* `clearStack`: gibt den gesamten Speicher frei. */
/*typedef struct Stack{
void *data; Zeiger auf den Nutzerdaten
struct Stack *next; Zeiger auf den Eintrag drunter
} StackNode; Stack oder StackNode kann beides als Namen für struct verwendet werden*/
// stack->next --> greift auf Struct zu und zeigt auf dann auf next
// Pushes data as pointer onto the stack.
// *stack ist Zeiger auf neustes oberste Element im Stack (wird zurückgegeben)
// *data soll gepusht werden
StackNode *push(StackNode *stack, void *data)
{
if(data != NULL)
{
StackNode *top;
top = malloc(sizeof(*top));
if(top == NULL)
{
return stack;
}
top->data = data;
if(stack == NULL)
{
top->next = NULL;
}
else
{
top->next = stack;
}
stack = top;
}
return stack;
}
// 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)
{
StackNode *nextNode = stack->next;
free(stack);
stack = nextNode;
}
return stack;
}
// Returns the data of the top element.
void *top(StackNode *stack)
{
if(stack == 0)
{
return NULL;
}
else
{
return stack->data;
}
}
// Clears stack and releases all memory.
void clearStack(StackNode *stack)
{
while(stack != NULL)
{
stack = pop(stack);
}
}

View File

@ -8,6 +8,10 @@ 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);