llist.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * linked list helper functions.
  4. *
  5. * Copyright (C) 2003 Glenn McGrath
  6. * Copyright (C) 2005 Vladimir Oleynik
  7. * Copyright (C) 2005 Bernhard Fischer
  8. *
  9. * Licensed under the GPL v2, see the file LICENSE in this tarball.
  10. */
  11. #include <stdlib.h>
  12. #include "libbb.h"
  13. #ifdef L_llist_add_to
  14. /* Add data to the start of the linked list. */
  15. llist_t *llist_add_to(llist_t *old_head, char *new_item)
  16. {
  17. llist_t *new_head;
  18. new_head = xmalloc(sizeof(llist_t));
  19. new_head->data = new_item;
  20. new_head->link = old_head;
  21. return (new_head);
  22. }
  23. #endif
  24. #ifdef L_llist_add_to_end
  25. /* Add data to the end of the linked list. */
  26. llist_t *llist_add_to_end(llist_t *list_head, char *data)
  27. {
  28. llist_t *new_item;
  29. new_item = xmalloc(sizeof(llist_t));
  30. new_item->data = data;
  31. new_item->link = NULL;
  32. if (list_head == NULL) {
  33. list_head = new_item;
  34. } else {
  35. llist_t *tail = list_head;
  36. while (tail->link)
  37. tail = tail->link;
  38. tail->link = new_item;
  39. }
  40. return list_head;
  41. }
  42. #endif
  43. #ifdef L_llist_free_one
  44. /* Free the current list element and advance to the next entry in the list.
  45. * Returns a pointer to the next element. */
  46. llist_t *llist_free_one(llist_t *elm)
  47. {
  48. llist_t *next = elm ? elm->link : NULL;
  49. free(elm);
  50. return next;
  51. }
  52. #endif
  53. #ifdef L_llist_free
  54. /* Recursively free all elements in the linked list. */
  55. void llist_free(llist_t *elm)
  56. {
  57. while ((elm = llist_free_one(elm)));
  58. }
  59. #endif