2

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!

sltcv
  • 23
  • 4
  • 2
    Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take [the SO tour](http://stackoverflow.com/tour), read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly learn how to create a [mcve]. – Some programmer dude Dec 05 '18 at 13:37
  • I cannot provide an example since it is not initalized :( – sltcv Dec 05 '18 at 13:38

1 Answers1

2

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.

Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98