44 lines
1.0 KiB
C
44 lines
1.0 KiB
C
#include <stdlib.h>
|
|
#include "stack.h"
|
|
|
|
typedef struct Stack_node {
|
|
void *data;
|
|
struct Stack_node *next;
|
|
} StackNode;
|
|
|
|
// Pushes data onto the stack.
|
|
// 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 and returns the new stack top.
|
|
// Caller must free the *data* itself.
|
|
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.
|
|
void *top(StackNode *stack) {
|
|
if (!stack) return NULL;
|
|
return stack->data;
|
|
}
|
|
|
|
// Clears entire stack (but does NOT free the data).
|
|
void clearStack(StackNode *stack) {
|
|
while (stack) {
|
|
StackNode *next = stack->next;
|
|
free(stack);
|
|
stack = next;
|
|
}
|
|
}
|