Fixed some things in stack.c, first test working

This commit is contained in:
Lukas Weber 2025-12-03 12:34:47 +01:00
parent 0bc9263b60
commit 036158fc59
3 changed files with 20 additions and 11 deletions

13
stack.c
View File

@ -12,12 +12,16 @@ StackNode *push(StackNode *stack, void *data)
{
if(!(stack)) { // check if stack is empty
stack = malloc(sizeof(StackNode));
if(!stack)
return NULL;
stack->stackData = data;
stack->below = NULL;
return stack;
}
StackNode* newStack = malloc(sizeof(StackNode));
if(!newStack)
return stack;
newStack->below = stack;
newStack->stackData = data;
stack = newStack;
@ -32,7 +36,6 @@ StackNode *pop(StackNode *stack)
if(stack) {
StackNode* temp = stack;
stack = stack->below;
free(temp->data);
temp->stackData = NULL;
free(temp);
temp = NULL;
@ -55,11 +58,7 @@ void *top(StackNode *stack)
// Clears stack and releases all memory.
void clearStack(StackNode *stack)
{
if(stack) {
do {
stack = pop(stack);
} while (stack->below);
pop(stack);
}
while(stack)
stack = pop(stack);
}

View File

@ -10,7 +10,7 @@ The latest element is taken from the stack. */
//TODO: passenden Datentyp als struct anlegen
typedef struct StackNode {
StackNode* below;
struct StackNode* below;
void* stackData;
} StackNode;

View File

@ -3,18 +3,28 @@
void test_firstNodeAddedCorrectly(void) {
StackNode* modelStack;
printf("\nStarting first test...\n");
StackNode* modelStack = malloc(sizeof(StackNode));
int modelData = 5;
modelStack->below = NULL;
modelStack->data = &modelData;
modelStack->stackData = &modelData;
StackNode* testStack = NULL;
int testData = 5;
testStack = push(testStack, &testData);
TEST_ASSERT_EQUAL_INT(*(modelStack->data), *(testStack->data));
TEST_ASSERT_EQUAL_INT(*(int*)modelStack->stackData, *(int*)testStack->stackData);
TEST_ASSERT_NULL(testStack->below);
clearStack(modelStack);
clearStack(testStack);
}
void setUp(void) {
}
void tearDown(void) {
}
int main(void) {