
ft_lstsize 함수는 list의 길이를 반환하는 함수다.
typedef struct s_list
{
void *content;
struct s_list *next;
} t_list;
int ft_lstsize(t_list *lst)
{
int size;
size = 0;
while (lst != 0)
{
size++;
lst = lst->next;
}
return (size);
}
리스트의 마지막은 NULL로 설정해 놓았으니 NULL이 나올 때까지 계속 이동하는 방식으로 구현하면 된다.
다만 Python에서는 List의 길이를 구할 때 해당 방식이 아니라 미리 생성할 때 구하고 저장하는 방식을 이용한다. cpython의 Include 항목 중 listobject.h 헤더 파일에서 확인할 수 있다.
https://github.com/python/cpython/blob/main/Include/cpython/listobject.h
typedef struct {
PyObject_VAR_HEAD
/* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
PyObject **ob_item;
/* ob_item contains space for 'allocated' elements. The number
* currently in use is ob_size.
* Invariants:
* 0 <= ob_size <= allocated
* len(list) == ob_size
* ob_item == NULL implies ob_size == allocated == 0
* list.sort() temporarily sets allocated to -1 to detect mutations.
*
* Items must normally not be NULL, except during construction when
* the list is not yet visible outside the function that builds it.
*/
Py_ssize_t allocated;
} PyListObject;
아래와 같은 예시를 들면 더 이해가 될 것 같다.
개인적으로 나는 t_list라고 선언한 친구를 t_node로 선언하는 것이 더 가독성이 좋지 않을까 생각을 했다.
typedef struct s_node
{
void *content;
struct s_node *next;
} t_node;
typedef struct s_list
{
t_list *head;
size_t len;
} t_list
이렇게 선언을 하여 list에 node를 추가하거나 삭제할 때 len를 조정해주는 것이다.
그럼 길이가 필요할 때는 바로 len 값을 반환해주면 되므로 굳이 계산을 다시 할 필요가 없다.