stack.c funktion und typedef struct in .h geschrieben
This commit is contained in:
parent
c325131503
commit
1c1ba9e471
30
stack.c
30
stack.c
@ -10,24 +10,54 @@
|
|||||||
// Pushes data as pointer onto the stack.
|
// Pushes data as pointer onto the stack.
|
||||||
StackNode *push(StackNode *stack, void *data)
|
StackNode *push(StackNode *stack, void *data)
|
||||||
{
|
{
|
||||||
|
// Neues Stack-Element erstellen
|
||||||
|
StackNode *newNode = malloc(sizeof(StackNode));
|
||||||
|
if (!newNode) {
|
||||||
|
return stack; // oder NULL, je nach Fehlerstrategie
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
newNode->data = data;
|
||||||
|
newNode->next = stack; // bisheriger Stack wird nach unten geschoben
|
||||||
|
|
||||||
|
return newNode; // neuer Kopf des Stacks
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deletes the top element of the stack (latest added element) and releases its memory. (Pointer to data has to be
|
// Deletes the top element of the stack (latest added element) and releases its memory. (Pointer to data has to be
|
||||||
// freed by caller.)
|
// freed by caller.)
|
||||||
StackNode *pop(StackNode *stack)
|
StackNode *pop(StackNode *stack)
|
||||||
{
|
{
|
||||||
|
if (stack == NULL)
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
StackNode *newTop = stack->next;
|
||||||
|
|
||||||
|
// Daten gehen verloren!
|
||||||
|
// Caller KANN sie nicht freigeben.
|
||||||
|
free(stack);
|
||||||
|
|
||||||
|
return newTop;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns the data of the top element.
|
// Returns the data of the top element.
|
||||||
void *top(StackNode *stack)
|
void *top(StackNode *stack)
|
||||||
{
|
{
|
||||||
|
if (stack == NULL)
|
||||||
|
return NULL; // kein Element im Stack
|
||||||
|
|
||||||
|
return stack->data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clears stack and releases all memory.
|
// Clears stack and releases all memory.
|
||||||
void clearStack(StackNode *stack)
|
void clearStack(StackNode *stack)
|
||||||
{
|
{
|
||||||
|
StackNode *current = stack;
|
||||||
|
|
||||||
|
while (current != NULL)
|
||||||
|
{
|
||||||
|
StackNode *next = current->next;
|
||||||
|
free(current);
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
4
stack.h
4
stack.h
@ -8,6 +8,10 @@ The latest element is taken from the stack. */
|
|||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
//TODO: passenden Datentyp als struct anlegen
|
//TODO: passenden Datentyp als struct anlegen
|
||||||
|
typedef struct Node {
|
||||||
|
void *data;
|
||||||
|
struct Node *next;
|
||||||
|
} StackNode;
|
||||||
|
|
||||||
// Pushes data as pointer onto the stack.
|
// Pushes data as pointer onto the stack.
|
||||||
StackNode *push(StackNode *stack, void *data);
|
StackNode *push(StackNode *stack, void *data);
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user