akadjoker

ft list

Mar 30th, 2022
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1.  
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. typedef struct s_list
  7. {
  8. int content;
  9. struct s_list *next;
  10. } t_list;
  11.  
  12. t_list *ft_lstnew(int data)
  13. {
  14. t_list *new;
  15.  
  16. new = (t_list *)malloc(sizeof(t_list));
  17. if (new == NULL)
  18. return (NULL);
  19. new->content = data;
  20. new->next = NULL;
  21. return (new);
  22. }
  23.  
  24.  
  25. t_list *ft_lstlast(t_list *lst)
  26. {
  27. if (lst == NULL)
  28. return (NULL);
  29. while (lst->next != NULL)
  30. lst = lst->next;
  31. return (lst);
  32. }
  33.  
  34. void ft_lstdelone(t_list *lst)
  35. {
  36. if (lst == NULL)
  37. return ;
  38. free(lst);
  39. lst = NULL;
  40. }
  41.  
  42. int ft_lstsize(t_list *lst)
  43. {
  44. int size;
  45.  
  46. size = 0;
  47. while (lst != NULL)
  48. {
  49. lst = lst->next;
  50. size++;
  51. }
  52. return (size);
  53. }
  54.  
  55. void ft_lstadd_back(t_list **lst, t_list *new)
  56. {
  57. t_list *last;
  58.  
  59. if (lst)
  60. {
  61. if (!*lst)
  62. *lst = new;
  63. else
  64. {
  65. last = ft_lstlast(*lst);
  66. last->next = new;
  67. }
  68. }
  69. }
  70.  
  71. void ft_lstadd_front(t_list **lst, t_list *new)
  72. {
  73. if (lst == NULL || new == NULL)
  74. return ;
  75. new->next = *lst;
  76. *lst = new;
  77. }
  78.  
  79.  
  80. void ft_lstclear(t_list **lst)
  81. {
  82. t_list *curr;
  83. t_list *next;
  84.  
  85. curr = *lst;
  86. while (curr)
  87. {
  88. next = curr->next;
  89. ft_lstdelone(curr);
  90. curr = next;
  91. }
  92. *lst = NULL;
  93. }
  94.  
  95. void ft_lstiter(t_list *lst, void (*f)(int))
  96. {
  97. if (lst == NULL || f == NULL)
  98. return ;
  99. while (lst)
  100. {
  101. f(lst->content);
  102. lst = lst->next;
  103. }
  104. }
  105.  
  106.  
  107.  
  108. void print_list( int data)
  109. {
  110. printf("data: %d \n",data);
  111. }
  112.  
  113. int main()
  114. {
  115. t_list *root = ft_lstnew(0);
  116. t_list *n1 = ft_lstnew(1);
  117. t_list *n2 = ft_lstnew(2);
  118. t_list *n3 = ft_lstnew(3);
  119. t_list *n4 = ft_lstnew(4);
  120. t_list *n5 = ft_lstnew(10);
  121.  
  122. ft_lstadd_front(&root,n1);
  123. ft_lstadd_front(&root,n2);
  124. ft_lstadd_front(&root,n3);
  125. ft_lstadd_front(&root,n4);
  126. ft_lstadd_back(&root,n5);
  127.  
  128. ft_lstiter(root,print_list);
  129.  
  130. ft_lstclear(&root);
  131.  
  132. // printf("\n total ; %d \n",number);
  133. }
  134.  
Advertisement
Add Comment
Please, Sign In to add comment