/* * File: * list.c */ #include #include "list.h" list newList() { /* Allocate space for the list. */ list foo = (list) malloc(sizeof(struct LIST)); /* Sanity check. */ if (!foo) return 0; /* Initialize the fields. */ foo->head = (node *) NULL; foo->current = (node *) NULL; foo->length = 0; /* Return the new list. */ return foo; } /* newList() */ void *getCurrentContents(list ls) { if ((ls) && (ls->current) && (ls->current->contents)) return ls->current->contents; return NULL; } /* getCurrentContents(list) */ int addAfterCurrent(list ls, void *val) { node *new = (node *)malloc(sizeof(node)); if (!new) return 0; new->contents = val; /* If there is a current element... */ if (ls->current) { /* Rearrange pointers. */ new->next = ls->current->next; if (ls->current->next) ls->current->next->prev = new; new->prev = ls->current; ls->current->next = new; ++(ls->length); } else { /* Otherwise, create the first element. */ new->next = new; new->prev = new; ls->head = new; ls->current = new; ls->current->next = new; ls->current->prev = new; ls->length = 1; } return 1; } /* addAfterCurrent(list, void *) */ int advance(list ls) { /* If the list is empty, give up. */ if ((!ls->current) || (!ls->current->next)) return 0; ls->current = ls->current->next; return 1; } /* advance(list) */ int deleteCurrent(list ls) { node *tmp = ls->current; /* Verify that the list is nonempty. */ if (!ls->current) return 0; /* If the list has one element, set everything to null. */ if (ls->length == 1) { ls->current->next = NULL; ls->current->prev = NULL; ls->current = NULL; ls->head = NULL; ls->length = 0; } /* List has more than one element */ else { ls->current->prev->next = ls->current->next; ls->current->next->prev = ls->current->prev; /* Advance current */ ls->current = ls->current->next; /* Decrease the length. */ --(ls->length); /* That's it, we're done. */ } /* Free the memory associated with the current element. */ free(tmp); tmp = NULL; return 1; } /* deleteCurrent(list) */ int moveCursorToHead(list ls) { if ((!ls) || (!ls->head) || (!ls->current)) return 0; ls->current = ls->head; return 1; } /* moveCursorToHead(list) */