#include #include #include #include #include "lifo.h" #define LMAGIC 0xA5A5A5A5 // an element in a lifo struct erec { void *data; struct erec * next; }; // a lifo struct lrec { int magic; // used to mark a valid lifo struct erec * head; // last element added to the lifo int nume; // number of elements in the lifo }; // initializes an existing lifo struct lrec * Lnew() { struct lrec * lp; lp = (struct lrec *)malloc(sizeof(struct lrec)); if (lp) { lp->magic = LMAGIC; lp->head = NULL; lp->nume = 0; } else // lp is NULL { errno = ENOMEM; return NULL; } return lp; } // add an item to the lifo int Ladd(struct lrec * lp, void *data) { struct erec * ep; if (!lp || lp->magic != LMAGIC) { errno = EBADL; return -1; } ep = (struct erec *)malloc(sizeof(struct erec)); // allocate new element if (ep) { ep->data = data; ep->next = lp->head; lp->head = ep; lp->nume++; } else // ep is NULL, malloc failed { errno = ENOMEM; return -1; } return 0; } // remove an item from the lifo void * Lremove(struct lrec * lp) { if (!lp || lp->magic != LMAGIC) { errno = EBADL; return NULL; } if (lp->nume >= 1) // first be sure there is data in the lifo { void *data; struct erec *ep; ep = lp->head; lp->head = lp->head->next; lp->nume--; data = ep->data; free(ep); return data; } else // no data in the lifo { errno = ENODATA; return NULL; } } // return the head item of the lifo void * Lshow(struct lrec * lp) { if (!lp || lp->magic != LMAGIC) { errno = EBADL; return NULL; } if (lp->nume >= 1) // make sure there is data in the lifo { return lp->head->data; } else // no data in the lifo { errno = ENODATA; return NULL; } } // move the head item to the tail of the lifo // and return the new head item int Lfree(struct lrec * lp) { if (!lp || lp->magic != LMAGIC) { errno = EBADL; return -1; } while (lp->nume >= 1) // make sure there is data in the lifo { struct erec *ep; ep = lp->head; lp->head = lp->head->next; lp->nume--; free(ep); } return 0; }