list.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "list.h"
  2. ListNode *list_init_head(void* data) {
  3. ListNode *new = (ListNode *) malloc(sizeof(ListNode));
  4. new->data = data;
  5. new->next = NULL;
  6. return new;
  7. }
  8. ListNode *list_add(ListNode *head, void* data) {
  9. ListNode *new = (ListNode *) malloc(sizeof(ListNode));
  10. new->data = data;
  11. new->next = NULL;
  12. if (head == NULL)
  13. head = new;
  14. else {
  15. ListNode *it;
  16. for (it = head; it->next != NULL; it = it->next)
  17. ;
  18. it->next = new;
  19. }
  20. return head;
  21. }
  22. ListNode *list_find(ListNode *head, void* data) {
  23. ListNode *it;
  24. for (it = head; it != NULL; it = it->next)
  25. if (it->data == data)
  26. break;
  27. return it;
  28. }
  29. ListNode *list_element_at(ListNode *head, uint16_t index) {
  30. ListNode *it;
  31. uint16_t i;
  32. for (it = head, i = 0; it != NULL && i < index; it = it->next, i++);
  33. return it;
  34. }
  35. ListNode *list_remove(ListNode *head, ListNode *ep) {
  36. if (head == ep) {
  37. ListNode *new_head = head->next;
  38. free(head);
  39. return new_head;
  40. }
  41. ListNode *it;
  42. for (it = head; it->next != ep; it = it->next)
  43. ;
  44. it->next = ep->next;
  45. free(ep);
  46. return head;
  47. }
  48. void list_free(ListNode *head) {
  49. ListNode *it = head, *tmp;
  50. while (it != NULL) {
  51. tmp = it;
  52. it = it->next;
  53. free(tmp);
  54. }
  55. }