#include #include #include "stack.h" //TODO: grundlegende Stackfunktionen implementieren: /* * `push`: legt ein Element oben auf den Stack, * `pop`: entfernt das oberste Element, * `top`: liefert das oberste Element zurück, * `clearStack`: gibt den gesamten Speicher frei. */ // Pushes data as pointer onto the stack. StackNode *push(StackNode *stack, void *data) { StackNode *newNode = (StackNode *)malloc(sizeof(StackNode)); if(newNode == NULL) { fprintf(stderr,"Fehler! Der Speicher für den neuen StackNode konnte nicht allokiert werden!\n"); return stack; } newNode->data = data; //saves data in newNode newNode->next = stack; //pushes the newNode on top of stack (newNode->next points to previous Top-Node) 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) { fprintf(stderr,"Fehler! Stack darf zum poppen nicht leer sein!\n"); return stack; } StackNode *old = stack; //temporary pointer to old top of stack stack= stack->next; //update stack pointer to point to next element free(old); //free the memory of the old StackNode (old->data is not beeing freed) return stack; } // Returns the data of the top element. void *top(StackNode *stack) { if (stack == NULL) { fprintf(stderr,"Fehler! Kann von einem leeren Stack nicht das oberste Element lesen!\n"); return NULL; } void *data = stack->data; return data; } // Clears stack and releases all memory. void clearStack(StackNode *stack) { StackNode *current = stack; StackNode *next; while (current != NULL) { next = current->next; if (current->data != NULL) { free(current->data); current->data = NULL; } free(current); current = NULL; current = next; } }