Ich hab jetzt ehrlich gesagt keine Lust mich durch die ganzen Fehler zu wuseln, deshalb kriegste meine funktionierende Lösung. Kompiliert fehlerfrei und in meinem Test gabs auch keine Mem Leaks. Kann aber trotzdem Fehler enthalten.
Gespeichert wird hier der Pointer auf einen String.
Code:
#ifndef LIST_H
#define LIST_H
typedef struct Node {
char *dirpath;
struct Node *pNext;
} TNode;
void Prepend(TNode **pList, char const *path);
void Append(TNode **pList, char const *path);
void Delete(TNode **pList, char const *path);
void DeleteAll(TNode *pPath);
#endif
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
/* Make new node */
static TNode *MakeNode(char const *path) {
TNode *const pNewNode = malloc(sizeof(*pNewNode));
if(pNewNode == 0) {
fprintf(stderr, "MakeNode(): No memory!\n");
}
if(1 > strlen(path)) {
fprintf(stderr, "MakeNode(): Warning! Empty directory is inserted!");
}
pNewNode->dirpath = malloc(strlen(path)+1);
strcpy(pNewNode->dirpath, path);
pNewNode->pNext = 0;
return pNewNode;
}
//add node at start
void Prepend(TNode **pList, char const *path) {
TNode *pNewNode = MakeNode(path);
pNewNode->pNext = *pList;
*pList = pNewNode;
}
//add node at end
void Append(TNode **pList, char const *path) {
TNode *pNewNode = MakeNode(path);
TNode *pNode = *pList;
TNode *pPrev = *pList;
if(*pList == 0) { //empty list
*pList = pNewNode;
}else{
while(pNode != 0) {
pPrev = pNode;
pNode = pNode->pNext;
}
pPrev->pNext = pNewNode; //catenation with the last new node
}
}
void Delete(TNode **pList, char const *path) {
TNode *pPrev = *pList;
TNode *pNode = *pList;
while(pNode != 0) {
if(strcmp(pNode->dirpath, path) == 0) {
pPrev->pNext = pNode->pNext;
free(pNode->dirpath);
free(pNode); pNode = 0;
break;
}
pPrev = pNode;
pNode = pNode->pNext;
}
}
void DeleteAll(TNode *pPath) {
TNode *pNode = 0; //Pointer
while(pPath != 0) { //stop if end of list reached
pNode = pPath;
pPath = pNode->pNext; //next node
free(pNode->dirpath);
free(pNode); pNode = 0; //delete pointer and set to 0
}
}
mfg
Lesezeichen