Search code examples
clistsentinel

C: using sentinels on lists


Hello so I am learning linked lists and I have to write several functions by using a sentinel. I have this definition: A sentinel is a fake element that is the first element of the list. An empty list is then a single sentinel and not a NULL pointer.

I need initialise the sentinel of an empty list

void list_init(struct list *list);

and check if the list is empty (return true is empty)

int list_is_empty(struct list *list);

but I am completely lost, could you help me out, thanks!


Solution

  • A linked list node always has a next member

    struct list
    {
        int data;
        struct list *next;
    };
    

    When you create your sentinel you initialize next to NULL

    void list_init(struct list *list)
    {
        list->data = -1;
        list->next = NULL;
    }
    
    
    struct list *head = malloc(sizeof(struct list));
    list_init(head);
    

    Now the head has a next member of NULL so all you have to do is check if next equals NULL

    int list_is_empty(struct list *list)
    {
        if (list->next == NULL) return 1;
    
        return 0;
    }
    

    One you add one node head->next becomes NOT NULL and you will know the list is not empty. But you have to make sure that you always pass the head to the list_functions.