From b0826ec05731a983ed11cf9082650b1b5f7f42e5 Mon Sep 17 00:00:00 2001 From: Jonas Date: Fri, 21 Nov 2025 00:32:57 +0100 Subject: [PATCH] stack completed --- I2_Dobble/stack.c | 23 +++++++++++++++++++++++ I2_Dobble/stack.h | 5 +++++ 2 files changed, 28 insertions(+) diff --git a/I2_Dobble/stack.c b/I2_Dobble/stack.c index e3a90d4..bdcec8e 100644 --- a/I2_Dobble/stack.c +++ b/I2_Dobble/stack.c @@ -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; + } } \ No newline at end of file diff --git a/I2_Dobble/stack.h b/I2_Dobble/stack.h index f7d542d..e88e8f0 100644 --- a/I2_Dobble/stack.h +++ b/I2_Dobble/stack.h @@ -8,6 +8,11 @@ The latest element is taken from the stack. */ #include //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);