ft_list_size — Count Linked List Elements
Allowed functions: none
Write a function that returns the number of elements in the linked list that's passed to it.
int ft_list_size(t_list *begin_list);
You must use the following structure, and turn it in as a file called ft_list.h:
typedef struct s_list
{
struct s_list *next;
void *data;
} t_list;
Solution
Download ft_list_size.c#include "ft_list.h"
int ft_list_size(t_list *begin_list) {
int size = 0;
while (begin_list) {
size++;
begin_list = begin_list->next;
}
return size;
}
How It Works
Goal: Count the number of elements in a linked list.
Approach: Traverse the list from head to tail, incrementing a counter at each node.
Step by step:
- Initialize a
sizecounter to 0. - Loop while
begin_listis not NULL, incrementingsizeeach iteration. - Advance the pointer to the next node with
begin_list = begin_list->next. - Return the final count once the end of the list (NULL) is reached.
Key concept: Linked list traversal using a while loop that stops at NULL.