File tree Expand file tree Collapse file tree 1 file changed +89
-0
lines changed
0x13-more_singly_linked_lists Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include "lists.h"
2
+
3
+ size_t looped_listint_count (listint_t * head );
4
+ size_t free_listint_safe (listint_t * * h );
5
+
6
+ /**
7
+ * looped_listint_count - Counts the number of unique nodes
8
+ * @head: A pointer to the head of the list
9
+ * Return: return 0
10
+ */
11
+ size_t looped_listint_count (listint_t * head )
12
+ {
13
+ listint_t * tortoise , * hare ;
14
+ size_t nodes = 1 ;
15
+
16
+ if (head == NULL || head -> next == NULL )
17
+ return (0 );
18
+
19
+ tortoise = head -> next ;
20
+ hare = (head -> next )-> next ;
21
+
22
+ while (hare )
23
+ {
24
+ if (tortoise == hare )
25
+ {
26
+ tortoise = head ;
27
+ while (tortoise != hare )
28
+ {
29
+ nodes ++ ;
30
+ tortoise = tortoise -> next ;
31
+ hare = hare -> next ;
32
+ }
33
+
34
+ tortoise = tortoise -> next ;
35
+ while (tortoise != hare )
36
+ {
37
+ nodes ++ ;
38
+ tortoise = tortoise -> next ;
39
+ }
40
+
41
+ return (nodes );
42
+ }
43
+
44
+ tortoise = tortoise -> next ;
45
+ hare = (hare -> next )-> next ;
46
+ }
47
+
48
+ return (0 );
49
+ }
50
+
51
+ /**
52
+ * free_listint_safe - Frees a list safely
53
+ * @h: a pointer to the address
54
+ * Return: the size of the list
55
+ * Description: set head to NULL
56
+ */
57
+ size_t free_listint_safe (listint_t * * h )
58
+ {
59
+ listint_t * tmp ;
60
+ size_t nodes , index ;
61
+
62
+ nodes = looped_listint_count (* h );
63
+
64
+ if (nodes == 0 )
65
+ {
66
+ for (; h != NULL && * h != NULL ; nodes ++ )
67
+ {
68
+ tmp = (* h )-> next ;
69
+ free (* h );
70
+ * h = tmp ;
71
+ }
72
+ }
73
+
74
+ else
75
+ {
76
+ for (index = 0 ; index < nodes ; index ++ )
77
+ {
78
+ tmp = (* h )-> next ;
79
+ free (* h );
80
+ * h = tmp ;
81
+ }
82
+
83
+ * h = NULL ;
84
+ }
85
+
86
+ h = NULL ;
87
+
88
+ return (nodes );
89
+ }
You can’t perform that action at this time.
0 commit comments