Compare commits
No commits in common. "43a953eaa63dd8e5c2b478b95f12a73cc7c6fe8a" and "63f92a83fd148317da96ab5be921a69d3c4ad27f" have entirely different histories.
43a953eaa6
...
63f92a83fd
52
stack.c
52
stack.c
@ -1,43 +1,33 @@
|
|||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include "stack.h"
|
#include "stack.h"
|
||||||
|
|
||||||
typedef struct Stack_node {
|
//TODO: grundlegende Stackfunktionen implementieren:
|
||||||
void *data;
|
/* * `push`: legt ein Element oben auf den Stack,
|
||||||
struct Stack_node *next;
|
* `pop`: entfernt das oberste Element,
|
||||||
} StackNode;
|
* `top`: liefert das oberste Element zurück,
|
||||||
|
* `clearStack`: gibt den gesamten Speicher frei. */
|
||||||
|
|
||||||
// Pushes data onto the stack.
|
// Pushes data as pointer onto the stack.
|
||||||
// Returns the new top of the stack.
|
StackNode *push(StackNode *stack, void *data)
|
||||||
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 and returns the new stack top.
|
// Deletes the top element of the stack (latest added element) and releases its memory. (Pointer to data has to be
|
||||||
// Caller must free the *data* itself.
|
// freed by caller.)
|
||||||
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 at the top of the stack.
|
// Returns the data of the top element.
|
||||||
void *top(StackNode *stack) {
|
void *top(StackNode *stack)
|
||||||
if (!stack) return NULL;
|
{
|
||||||
return stack->data;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clears entire stack (but does NOT free the data).
|
// Clears stack and releases all memory.
|
||||||
void clearStack(StackNode *stack) {
|
void clearStack(StackNode *stack)
|
||||||
while (stack) {
|
{
|
||||||
StackNode *next = stack->next;
|
|
||||||
free(stack);
|
}
|
||||||
stack = next;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Loading…
x
Reference in New Issue
Block a user