how to check if a linked list is empty

c, linked-list

Solution

Intro:

There are usually two ways to use linked lists: with a root element and without.

Without a root, your list pointer is NULL when the list is empty:

node *list;
...
if (list == NULL) { /* empty list */ }

With root, there is always one element. But it can be used in two ways:

Either simply to provide a pointer to the first element.

node *root;
...
if (root->next == NULL) { /* empty list */ }

Or to have the last element link back to the root to form a cycle. This concept has the advantage that the "next" element is never NULL and you thus don't need to check for it. In this case, the list is empty if the root points back to itself.

node *root;
...
if (root->next == root) { /* empty list */ }

Answer:

Now, according to your description, you have allocated a node. This either means you want the "root" approach (second or third example). But if you want to go with the first variant, you must not allocate the node, since it doesn't hold data.

For the "root" approach, you indeed have one (and only one) node that doesn't hold data. But for simple linked lists, all nodes must contain data.

Problem

I'm new to C and have a question. How would I check if a linked list is empty? I have a struct _node ``` typedef struct _node{ int data; struct _node *next; }node; ``` If I have initialized `node *list`, but didn't do anything to it (i.e didn't assign `list->data` a value), how would I check if it's empty? I tried `if (node == NULL){break}` but didn't work. Thanks for the help!

Original source