3
0

llist.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 "libbb.h"
  13. /* Add data to the start of the linked list. */
  14. void llist_add_to(llist_t **old_head, void *data)
  15. {
  16. llist_t *new_head = xmalloc(sizeof(llist_t));
  17. new_head->data = data;
  18. new_head->link = *old_head;
  19. *old_head = new_head;
  20. }
  21. /* Add data to the end of the linked list. */
  22. void llist_add_to_end(llist_t **list_head, void *data)
  23. {
  24. llist_t *new_item = xmalloc(sizeof(llist_t));
  25. new_item->data = data;
  26. new_item->link = NULL;
  27. if (!*list_head)
  28. *list_head = new_item;
  29. else {
  30. llist_t *tail = *list_head;
  31. while (tail->link)
  32. tail = tail->link;
  33. tail->link = new_item;
  34. }
  35. }
  36. /* Remove first element from the list and return it */
  37. void *llist_pop(llist_t **head)
  38. {
  39. void *data, *next;
  40. if (!*head)
  41. return NULL;
  42. data = (*head)->data;
  43. next = (*head)->link;
  44. free(*head);
  45. *head = next;
  46. return data;
  47. }
  48. /* Unlink arbitrary given element from the list */
  49. void llist_unlink(llist_t **head, llist_t *elm)
  50. {
  51. llist_t *crt;
  52. if (!(elm && *head))
  53. return;
  54. if (elm == *head) {
  55. *head = (*head)->link;
  56. return;
  57. }
  58. for (crt = *head; crt; crt = crt->link) {
  59. if (crt->link == elm) {
  60. crt->link = elm->link;
  61. return;
  62. }
  63. }
  64. }
  65. /* Recursively free all elements in the linked list. If freeit != NULL
  66. * call it on each datum in the list */
  67. void llist_free(llist_t *elm, void (*freeit) (void *data))
  68. {
  69. while (elm) {
  70. void *data = llist_pop(&elm);
  71. if (freeit)
  72. freeit(data);
  73. }
  74. }
  75. #ifdef UNUSED
  76. /* Reverse list order. */
  77. llist_t *llist_rev(llist_t *list)
  78. {
  79. llist_t *rev = NULL;
  80. while (list) {
  81. llist_t *next = list->link;
  82. list->link = rev;
  83. rev = list;
  84. list = next;
  85. }
  86. return rev;
  87. }
  88. #endif