llist.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. * Copyright (C) 2006 Rob Landley <rob@landley.net>
  9. *
  10. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  11. */
  12. #include <stdlib.h>
  13. #include "libbb.h"
  14. /* Add data to the start of the linked list. */
  15. void llist_add_to(llist_t **old_head, void *data)
  16. {
  17. llist_t *new_head = xmalloc(sizeof(llist_t));
  18. new_head->data = data;
  19. new_head->link = *old_head;
  20. *old_head = new_head;
  21. }
  22. /* Add data to the end of the linked list. */
  23. void llist_add_to_end(llist_t **list_head, void *data)
  24. {
  25. llist_t *new_item = xmalloc(sizeof(llist_t));
  26. new_item->data = data;
  27. new_item->link = NULL;
  28. if (!*list_head) *list_head = new_item;
  29. else {
  30. llist_t *tail = *list_head;
  31. while (tail->link) tail = tail->link;
  32. tail->link = new_item;
  33. }
  34. }
  35. /* Remove first element from the list and return it */
  36. void *llist_pop(llist_t **head)
  37. {
  38. void *data;
  39. if(!*head) data = *head;
  40. else {
  41. void *next = (*head)->link;
  42. data = (*head)->data;
  43. free(*head);
  44. *head = next;
  45. }
  46. return data;
  47. }
  48. /* Recursively free all elements in the linked list. If freeit != NULL
  49. * call it on each datum in the list */
  50. void llist_free(llist_t *elm, void (*freeit)(void *data))
  51. {
  52. while (elm) {
  53. void *data = llist_pop(&elm);
  54. if (freeit) freeit(data);
  55. }
  56. }
  57. /* Reverse list order. Useful since getopt32 saves option params
  58. * in reverse order */
  59. llist_t* rev_llist(llist_t *list)
  60. {
  61. llist_t *new = NULL;
  62. while (list) {
  63. llist_t *next = list->link;
  64. list->link = new;
  65. new = list;
  66. list = next;
  67. }
  68. return new;
  69. }