0x12. C Singly linked lists Task 1 - humtej1204/holbertonschool-low_level_programming GitHub Wiki

1. List length

mandatory

Write a function that returns the number of elements in a linked list_t list.

  • Prototype: size_t list_len(const list_t *h);
julien@ubuntu:~/0x12. Singly linked lists$ cat 1-main.c
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "lists.h"

/**
 * main - check the code
 *
 * Return: Always 0.
 */
int main(void)
{
    list_t *head;
    list_t *new;
    list_t hello = {"World", 5, NULL};
    size_t n;

    head = &hello;
    new = malloc(sizeof(list_t));
    if (new == NULL)
    {
        printf("Error\n");
        return (1);
    }
    new->str = strdup("Hello");
    new->len = 5;
    new->next = head;
    head = new;
    n = list_len(head);
    printf("-> %lu elements\n", n);
    free(new->str);
    free(new);
    return (0);
}
julien@ubuntu:~/0x12. Singly linked lists$ gcc -Wall -pedantic -Werror -Wextra -std=gnu89 1-main.c 1-list_len.c -o b
julien@ubuntu:~/0x12. Singly linked lists$ ./b 
-> 2 elements
julien@ubuntu:~/0x12. Singly linked lists$ 

Repo:

  • GitHub repository: holbertonschool-low_level_programming
  • Directory: 0x12-singly_linked_lists
  • File: 1-list_len.c
⚠️ **GitHub.com Fallback** ⚠️