stack angepasst, test_stack.c hinzugefuegt

This commit is contained in:
Rebekka Haemmerl 2025-12-05 09:29:15 +01:00
parent 8c0ff19529
commit 127c7aa8e7
3 changed files with 75 additions and 6 deletions

16
stack.c
View File

@ -10,7 +10,11 @@
// Pushes data as pointer onto the stack.
StackNode *push(StackNode *stack, void *data)
{
if(stack && data){
if (!data)
{
return stack; //Nichts pushen
}
//if(stack && data){
StackNode *t = (StackNode *)malloc(sizeof(StackNode));
if(!t)
{
@ -19,7 +23,7 @@ StackNode *push(StackNode *stack, void *data)
t->next = stack;
t->data = data;
return t; //Gibt den ersten StackNode des Stacks zurueck
}
//}
return NULL;
}
@ -33,6 +37,10 @@ StackNode *pop(StackNode *stack)
free(stack);
return t;
}
else
{
return NULL;
}
}
// Returns the data of the top element.
@ -50,8 +58,8 @@ void clearStack(StackNode *stack)
{
while(stack)
{
StackNode *tmp = stack; //merkt sich den momentanen obersten KNoten
stack = stack->next; //setzt den obersten Knoten auf den zweiten im Stack
StackNode *tmp = stack; //merkt sich den momentanen obersten Knoten
stack = stack->next; //setzt den obersten Knoten auf den Zweiten im Stack
free(tmp->data);
free(tmp);
}

View File

@ -8,8 +8,8 @@ The latest element is taken from the stack. */
#include <stdlib.h>
//TODO: passenden Datentyp als struct anlegen
typedef{
int* data;
typedef struct StackNode {
void* data;
struct StackNode *next;
}StackNode;

61
test_stack.c Normal file
View File

@ -0,0 +1,61 @@
#include <stdlib.h>
#include "stack.h"
//Testfunkionen zu push, pull, top & clearStack schreiben
StackNode *push(StackNode *stack, void *data)
{
if (!data)
{
return stack; //Nichts pushen
}
//if(stack && data){
StackNode *t = (StackNode *)malloc(sizeof(StackNode));
if(!t)
{
return NULL; //Speicherfehler
}
t->next = stack;
t->data = data;
return t; //Gibt den ersten StackNode des Stacks zurueck
//}
return NULL;
}
// 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)
{
StackNode *t = stack->next; //Naechstes Element im Stack wird erstes Element
free(stack);
return t;
}
else
{
return NULL;
}
}
// Returns the data of the top element.
void *top(StackNode *stack)
{
if(stack)
{
return stack->data;
}
return NULL;
}
// Clears stack and releases all memory.
void clearStack(StackNode *stack)
{
while(stack)
{
StackNode *tmp = stack; //merkt sich den momentanen obersten Knoten
stack = stack->next; //setzt den obersten Knoten auf den Zweiten im Stack
free(tmp->data);
free(tmp);
}
}