list.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /* list.c -- functions supporting list operations */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include "list.h"
  5. /* local function prototype */
  6. static void CopyToNode(Item item, Node * pnode);
  7. /* interface functions */
  8. /* set the list to empty */
  9. void InitializeList(List * plist)
  10. {
  11. * plist = NULL;
  12. }
  13. /* returns true if list is empty */
  14. bool ListIsEmpty(const List * plist)
  15. {
  16. if (*plist == NULL)
  17. return true;
  18. else
  19. return false;
  20. }
  21. /* returns true if list is full */
  22. bool ListIsFull(const List * plist)
  23. {
  24. Node * pt;
  25. bool full;
  26. pt = (Node *) malloc(sizeof(Node));
  27. if (pt == NULL)
  28. full = true;
  29. else
  30. full = false;
  31. free(pt);
  32. return full;
  33. }
  34. /* returns number of nodes */
  35. unsigned int ListItemCount(const List * plist)
  36. {
  37. unsigned int count = 0;
  38. Node * pnode = *plist; /* set to start of list */
  39. while (pnode != NULL)
  40. {
  41. ++count;
  42. pnode = pnode->next; /* set to next node */
  43. }
  44. return count;
  45. }
  46. /* creates node to hold item and adds it to the end of */
  47. /* the list pointed to by plist (slow implementation) */
  48. bool AddItem(Item item, List * plist)
  49. {
  50. Node * pnew;
  51. Node * scan = *plist;
  52. pnew = (Node *) malloc(sizeof(Node));
  53. if (pnew == NULL)
  54. return false; /* quit function on failure */
  55. CopyToNode(item, pnew);
  56. pnew->next = NULL;
  57. if (scan == NULL) /* empty list, so place */
  58. *plist = pnew; /* pnew at head of list */
  59. else
  60. {
  61. while (scan->next != NULL)
  62. scan = scan->next; /* find end of list */
  63. scan->next = pnew; /* add pnew to end */
  64. }
  65. return true;
  66. }
  67. /* visit each node and execute function pointed to by pfun */
  68. void Traverse (const List * plist, void (* pfun)(Item item) )
  69. {
  70. Node * pnode = *plist; /* set to start of list */
  71. while (pnode != NULL)
  72. {
  73. (*pfun)(pnode->item); /* apply function to item */
  74. pnode = pnode->next; /* advance to next item */
  75. }
  76. }
  77. /* free memory allocated by malloc() */
  78. /* set list pointer to NULL */
  79. void EmptyTheList(List * plist)
  80. {
  81. Node * psave;
  82. while (*plist != NULL)
  83. {
  84. psave = (*plist)->next; /* save address of next node */
  85. free(*plist); /* free current node */
  86. *plist = psave; /* advance to next node */
  87. }
  88. }
  89. /* local function definition */
  90. /* copies an item into a node */
  91. static void CopyToNode(Item item, Node * pnode)
  92. {
  93. pnode->item = item; /* structure copy */
  94. }