linked_list.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <stdlib.h>
  2. #include "linked_list.h"
  3. int getLength(const struct ListNode_t* root) {
  4. int count = 0;
  5. while(root) {
  6. root = root->next;
  7. count += 1;
  8. }
  9. return count;
  10. }
  11. LinkedListStatus
  12. createNode(struct ListNode_t** emptyNode, struct ListNode_t* previousNode, void* data) {
  13. *emptyNode = malloc(sizeof(struct ListNode_t));
  14. if(*emptyNode == 0) {
  15. return LIST_CANT_ALLOCATE;
  16. }
  17. (*emptyNode)->data = data;
  18. (*emptyNode)->previous = previousNode;
  19. return LIST_OK;
  20. }
  21. LinkedListStatus addNode(struct ListNode_t** root, void* data) {
  22. // If there is no root node, add that first
  23. if(*root == 0) {
  24. return createNode(root, 0, data);
  25. }
  26. // Iterate until we find an empty node
  27. struct ListNode_t* base = *root;
  28. while(base->next) {
  29. base = base->next;
  30. }
  31. return createNode(&base->next, base, data);
  32. }
  33. LinkedListStatus removeNode(struct ListNode_t** root, const void* data) {
  34. if(*root == 0) {
  35. return LIST_NO_NODE;
  36. }
  37. struct ListNode_t* base = *root;
  38. while(base->data != data && base->next) {
  39. base = base->next;
  40. }
  41. // Delete node if data is matching
  42. if(base->data == data) {
  43. (base->previous)->next = base->next;
  44. (base->next)->previous = base->previous;
  45. free(base);
  46. return LIST_OK;
  47. }
  48. return LIST_NO_NODE;
  49. }
  50. LinkedListStatus removeAllNodes(struct ListNode_t** root) {
  51. struct ListNode_t* base = *root;
  52. struct ListNode_t* temp;
  53. while(base) {
  54. temp = base;
  55. base = base->next;
  56. free(temp);
  57. }
  58. (*root) = NULL;
  59. return LIST_OK;
  60. }