Skip to content

Commit 752f992

Browse files
committed
Refactor dlistint_len function for improved performance and clarity
Renamed variables for better readability and consistency Replaced while loop with a for loop for iterating through the list Removed unnecessary assignment and improved code structure Updated function documentation and comments
1 parent 1f51174 commit 752f992

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include "lists.h"
2+
3+
/**
4+
* dlistint_len - Returns the number of elements in a linked dlistint_t list.
5+
* @h: Pointer to head of the list.
6+
*
7+
* Return: The number of elements in the list.
8+
*/
9+
10+
size_t dlistint_len(const dlistint_t *h)
11+
{
12+
size_t count = 0;
13+
14+
/* Iterate through the list until reaching the end */
15+
while (h)
16+
{
17+
/* Increment the count for each node encountered */
18+
count++;
19+
/* Move to the next node */
20+
h = h->next;
21+
}
22+
return (count);
23+
}

0x17-doubly_linked_lists/1-main.c

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <stdlib.h>
2+
#include <string.h>
3+
#include <stdio.h>
4+
#include "lists.h"
5+
6+
/**
7+
* main - check the code
8+
*
9+
* Return: Always EXIT_SUCCESS.
10+
*/
11+
int main(void)
12+
{
13+
dlistint_t *head;
14+
dlistint_t *new;
15+
dlistint_t hello = {8, NULL, NULL};
16+
size_t n;
17+
18+
head = &hello;
19+
new = malloc(sizeof(dlistint_t));
20+
if (new == NULL)
21+
{
22+
dprintf(2, "Error: Can't malloc\n");
23+
return (EXIT_FAILURE);
24+
}
25+
new->n = 9;
26+
head->prev = new;
27+
new->next = head;
28+
new->prev = NULL;
29+
head = new;
30+
n = dlistint_len(head);
31+
printf("-> %lu elements\n", n);
32+
free(new);
33+
return (EXIT_SUCCESS);
34+
}

0x17-doubly_linked_lists/b

16.5 KB
Binary file not shown.

0 commit comments

Comments
 (0)