Advertisement
lidorcohen

Linked List Project Template

Jun 19th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. #define ITERATIVE 20
  6. #define RAND_MAX 100
  7.  
  8. typedef struct ls {
  9.     int data;
  10.     struct ls* next;
  11. } ls;
  12.  
  13. ls* createNode(int data);
  14. void append(ls* list, int data);
  15. void printList(ls* list);
  16. void freeListRecursive(ls** head);
  17.  
  18. int main(void)
  19. {
  20.     ls* mainList = createNode(1);
  21.  
  22.     // Write Here
  23.  
  24.     freeListRecursive(&mainList);
  25.     getchar();
  26.     return 0;
  27. }
  28.  
  29. /*
  30. Function creates a node with data
  31. input: integer data
  32. output: address of new struct
  33. */
  34. ls* createNode(int data)
  35. {
  36.     ls* list = (ls*)malloc(sizeof(ls));
  37.  
  38.     list->data = data;
  39.     list->next = NULL;
  40.  
  41.     return list;
  42. }
  43.  
  44. /*
  45. Function prints a linked list
  46. input: head list
  47. output: none
  48. */
  49. void printList(ls* lst)
  50. {
  51.     ls* curr = lst;
  52.  
  53.     do {
  54.         printf("%d -> ", lst->data);
  55.         lst = lst->next;
  56.     } while (lst);
  57.  
  58.     printf("NULL\n");
  59. }
  60.  
  61. /*
  62. Function takes a list and data and appends a new
  63. node to the end of the list inputed with the data given.
  64. input: list head and data
  65. output: none
  66. */
  67. void append(ls* list, int data)
  68. {
  69.     ls* curr = list;
  70.  
  71.     while (curr->next)
  72.     {
  73.         curr = curr->next;
  74.     }
  75.  
  76.     curr->next = createNode(data);
  77. }
  78.  
  79. /*
  80. Function frees all memory of a linked list
  81. input: a linked list
  82. output: none
  83. */
  84. void freeListRecursive(ls** head)
  85. {
  86.     if (*head != NULL) // if list not empty
  87.     {
  88.         if ((*head)->next != NULL) // end condition
  89.         {
  90.             freeListRecursive(&((*head)->next));
  91.         }
  92.         free(*head);
  93.     }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement