list.c 1.4 KB

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