3
0

llist.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 Reutner-Fischer
  8. * Copyright (C) 2006 Rob Landley <rob@landley.net>
  9. *
  10. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  11. */
  12. #include "libbb.h"
  13. /* Add data to the start of the linked list. */
  14. void FAST_FUNC 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 FAST_FUNC llist_add_to_end(llist_t **list_head, void *data)
  23. {
  24. while (*list_head)
  25. list_head = &(*list_head)->link;
  26. *list_head = xzalloc(sizeof(llist_t));
  27. (*list_head)->data = data;
  28. /*(*list_head)->link = NULL;*/
  29. }
  30. /* Remove first element from the list and return it */
  31. void* FAST_FUNC llist_pop(llist_t **head)
  32. {
  33. void *data = NULL;
  34. llist_t *temp = *head;
  35. if (temp) {
  36. data = temp->data;
  37. *head = temp->link;
  38. free(temp);
  39. }
  40. return data;
  41. }
  42. /* Unlink arbitrary given element from the list */
  43. void FAST_FUNC llist_unlink(llist_t **head, llist_t *elm)
  44. {
  45. if (!elm)
  46. return;
  47. while (*head) {
  48. if (*head == elm) {
  49. *head = (*head)->link;
  50. break;
  51. }
  52. head = &(*head)->link;
  53. }
  54. }
  55. /* Recursively free all elements in the linked list. If freeit != NULL
  56. * call it on each datum in the list */
  57. void FAST_FUNC llist_free(llist_t *elm, void (*freeit)(void *data))
  58. {
  59. while (elm) {
  60. void *data = llist_pop(&elm);
  61. if (freeit)
  62. freeit(data);
  63. }
  64. }
  65. /* Reverse list order. */
  66. llist_t* FAST_FUNC llist_rev(llist_t *list)
  67. {
  68. llist_t *rev = NULL;
  69. while (list) {
  70. llist_t *next = list->link;
  71. list->link = rev;
  72. rev = list;
  73. list = next;
  74. }
  75. return rev;
  76. }
  77. llist_t* FAST_FUNC llist_find_str(llist_t *list, const char *str)
  78. {
  79. while (list) {
  80. if (strcmp(list->data, str) == 0)
  81. break;
  82. list = list->link;
  83. }
  84. return list;
  85. }