#include #include #include #include "dll.h" #ifndef NULL #define NULL (void *)0 #endif DLLItem* makeDLLItem(char* data) { DLLItem *dlli = malloc(1 * sizeof(DLLItem)); dlli->prev = NULL; dlli->next = NULL; dlli->payload = malloc((strlen(data)+1) * sizeof(char)); strcpy(dlli->payload, data); return dlli; } DLL* makeDLL() { DLL *ret = malloc(1 * sizeof(DLL)); ret->head = NULL; ret->tail = NULL; ret->count = 0; return ret; } void addDLLHead(DLL *dllC, char* data) { DLLItem *item = makeDLLItem(data); if (dllC->head == NULL) { dllC->head = item; dllC->tail = item; dllC->count = 1; return; } dllC->head->prev = item; item->next = dllC->head; dllC->head = item; dllC->count++; } void freeDLLItem(DLLItem *dlli) { free(dlli->payload); free(dlli); } char* removeTail(DLL *dll) { if (dll->count<=0) return NULL; dll->count--; DLLItem *itm = dll->tail; DLLItem *tprev = itm->prev; if (tprev==NULL) { dll->head = NULL; dll->tail = NULL; return NULL; } dll->tail = tprev; tprev->next = NULL; char *rtn = malloc((strlen(itm->payload) + 1) * sizeof(char)); strcpy(rtn, itm->payload); freeDLLItem(itm); return rtn; } void printDLL(DLL *dll) { DLLItem *item = dll->head; while (item!=NULL) { printf("%s\n", item->payload); item = item->next; } } void freeDLL(DLL * dll) { DLLItem *item = dll->head; while (item!=NULL) { DLLItem * nextItem = item->next; freeDLLItem(item); item = nextItem; //item = item->next; } free(dll); } #ifndef DOTO int main(int argc, char const *argv[]) { DLL *dll = makeDLL(); addDLLHead(dll, "Geoff"); addDLLHead(dll, "Deepak"); addDLLHead(dll, "Dianna"); printDLL(dll); char* cc = removeTail(dll); if (cc!=NULL) { printf("REMOVE %s\n", cc); free(cc); } printDLL(dll); freeDLL(dll); return 0; } #endif