Compare commits

...

3 Commits

Author SHA1 Message Date
43a953eaa6 Merge pull request 'set-stack-push-function' (#2) from set-stack-push-function into main
Reviewed-on: #2
2025-12-02 00:45:19 +00:00
fonkou
c2955be947 fix stac.c 2025-12-02 01:42:34 +01:00
fonkou
2c8974b6c6 add typdef StackNode 2025-11-25 16:57:33 +01:00

52
stack.c
View File

@ -1,33 +1,43 @@
#include <stdlib.h> #include <stdlib.h>
#include "stack.h" #include "stack.h"
//TODO: grundlegende Stackfunktionen implementieren: typedef struct Stack_node {
/* * `push`: legt ein Element oben auf den Stack, void *data;
* `pop`: entfernt das oberste Element, struct Stack_node *next;
* `top`: liefert das oberste Element zurück, } StackNode;
* `clearStack`: gibt den gesamten Speicher frei. */
// Pushes data as pointer onto the stack. // Pushes data onto the stack.
StackNode *push(StackNode *stack, void *data) // Returns the new top of the stack.
{ StackNode *push(StackNode *stack, void *data) {
StackNode *node = malloc(sizeof(StackNode));
if (!node) return stack; // allocation failed → leave unchanged
node->data = data;
node->next = stack;
return node; // new top element
} }
// Deletes the top element of the stack (latest added element) and releases its memory. (Pointer to data has to be // Deletes the top element and returns the new stack top.
// freed by caller.) // Caller must free the *data* itself.
StackNode *pop(StackNode *stack) StackNode *pop(StackNode *stack) {
{ if (!stack) return NULL;
StackNode *next = stack->next;
free(stack); // free only the node, NOT the data
return next;
} }
// Returns the data of the top element. // Returns the data at the top of the stack.
void *top(StackNode *stack) void *top(StackNode *stack) {
{ if (!stack) return NULL;
return stack->data;
} }
// Clears stack and releases all memory. // Clears entire stack (but does NOT free the data).
void clearStack(StackNode *stack) void clearStack(StackNode *stack) {
{ while (stack) {
StackNode *next = stack->next;
} free(stack);
stack = next;
}
}