Skip to content

Commit 46cdd81

Browse files
committed
more commits
1 parent 808417a commit 46cdd81

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include "lists.h"
2+
#include <stdio.h>
3+
4+
size_t looped_listint_len(const listint_t *head);
5+
size_t print_listint_safe(const listint_t *head);
6+
7+
/**
8+
* looped_listint_len - Counts the number of unique nodes
9+
* @head: A pointer to the head of the list
10+
* Return: return 0
11+
*/
12+
size_t looped_listint_len(const listint_t *head)
13+
{
14+
const listint_t *tortoise, *hare;
15+
size_t nodes = 1;
16+
17+
if (head == NULL || head->next == NULL)
18+
return (0);
19+
20+
tortoise = head->next;
21+
hare = (head->next)->next;
22+
23+
while (hare)
24+
{
25+
if (tortoise == hare)
26+
{
27+
tortoise = head;
28+
while (tortoise != hare)
29+
{
30+
nodes++;
31+
tortoise = tortoise->next;
32+
hare = hare->next;
33+
}
34+
35+
tortoise = tortoise->next;
36+
while (tortoise != hare)
37+
{
38+
nodes++;
39+
tortoise = tortoise->next;
40+
}
41+
42+
return (nodes);
43+
}
44+
45+
tortoise = tortoise->next;
46+
hare = (hare->next)->next;
47+
}
48+
49+
return (0);
50+
}
51+
52+
/**
53+
* print_listint_safe - Prints a list
54+
* @head: A pointer to the head of the list
55+
* Return: The number of nodes in the list
56+
*/
57+
size_t print_listint_safe(const listint_t *head)
58+
{
59+
size_t nodes, index = 0;
60+
61+
nodes = looped_listint_len(head);
62+
63+
if (nodes == 0)
64+
{
65+
for (; head != NULL; nodes++)
66+
{
67+
printf("[%p] %d\n", (void *)head, head->n);
68+
head = head->next;
69+
}
70+
}
71+
72+
else
73+
{
74+
for (index = 0; index < nodes; index++)
75+
{
76+
printf("[%p] %d\n", (void *)head, head->n);
77+
head = head->next;
78+
}
79+
80+
printf("-> [%p] %d\n", (void *)head, head->n);
81+
}
82+
83+
return (nodes);
84+
}

0 commit comments

Comments
 (0)