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.

Answer from DarkDust on Stack Overflow
🌐
Quora
quora.com › What-is-the-best-way-to-check-if-a-linked-list-is-empty-or-not-in-C
What is the best way to check if a linked list is empty or not in C++? - Quora
Usually, you will use the Standard Template Library, where a linked list is implemented as std::list. In this case, you can just use the empty() method that returns true if the list is empty and false if it is not empt...
Top answer
1 of 2
1

First of all you don't need double pointer. Initialization with NULL is important here. (Denotes the empty list).

SortedList *list = NULL;

This has the benefit that now if you want to make changes to it pass it's address.

func(&list);

And checking the empty list would be

   void func(SortedList **list){
      if( *list == NULL )
        /* empty */
   }

This is usually the way lists are implemented.


In your case you simply allocated to a local variable and instead of returning the memory address you have overwritten the pointer's value with NULL - there is memory leak in the code.

With your code it will be something like. Yes all that the initialization does is assigning it to NULL. This is one easy way out towards checking the NULL. At the very beginning making it NULL basically denotes that list is empty.(which is the case generally).

2 of 2
0

list is a pointer to a pointer. The actual list is in the value it points to, so you need to dereference it.

An empty list is just a null pointer, so you don't need to allocate anything in init().

void init(SortedList** list)
{
    *list=NULL;
    printf("%p\n", *list);
}
void isEmpty(SortedList** list)
{
    printf("%p\n", *list);
    if(*list == NULL) printf("List is empty\n");]
}

And in the main function, you don't need a double pointer, you use the & (address-of) operator to get the address of a pointer variable.

int main()  
{
    SortedList *list;
    init(&list);
    printf("Initialization with succes\n");
    isEmpty(&list);

    return 0;
}

You only really need double pointers for functions that modify the list. So you could use an ordinary pointer for isEmpty:

void isEmpty(SortedList* list)
{
    printf("%p\n", list);
    if(list == NULL) printf("List is empty\n");]
}

and then call it as:

isEmpty(list);

But it's probably simplest to be consistent across all your functions.

🌐
Opengenus
discourse.opengenus.org › algorithm
Check if Linked List is Empty - algorithm - Discuss Career & Computing - OpenGenus
November 27, 2020 - This is a companion discussion topic for the original entry at http://iq.opengenus.org/check-if-linked-list-is-empty/
🌐
OpenGenus
iq.opengenus.org › check-if-linked-list-is-empty
Check if Linked List is Empty
November 27, 2020 - List contains:\n"; l1.printList(); } return 0; } ... Without a root, the list pointer is NULL when the list is empty. Pseudocode: bool isEmpty(node *list){ if (list == NULL) return true; else return false; } Implementation of Linked List without root is given below:
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 156691 › linked-lists-find-length-and-check-for-empty-list
Linked Lists: Find length and check for empty list - c++
In printList you currently allocate a node and then overwrite the pointer; drop that allocation to avoid a leak and just iterate from first. Your insertBack uses a local first that is never passed in; pass both first and last by reference so you can handle the empty-list case. In deleteFront, do not test first->info == 1; instead, check first != NULL before dereferencing, unlink the head, delete it, and set last = NULL if the list becomes empty.
🌐
Reddit
reddit.com › r/c_programming › any good reason to allow for empty linked list?
r/C_Programming on Reddit: Any good reason to allow for empty linked list?
October 18, 2023 -

Hello, I've been making a linked list, and talking about it with my dad too, he insists that you should be allowed to make an empty linked list, but I don't think there should be, since there's "no reason to store nothing."

Thoughts?

Edit: feel free to continue posting your thoughts, but after some thought, I'll reconsider allowing an empty list, since having the end user work around this issue would probably make it overall more work. Thank you very much for your input though! I'll let my dad know most of you agree with him 😂

Edit 2: alrighty, I've thought about it, I'll definitely be implementing the support for an empty linked list (though I'll have to rewrite a large chunk of code, rip lol) I definitely enjoyed talking with you guys, and I look forward to finally posting my implementation.

Top answer
1 of 18
52
Suppose the bank has a list of debts that you have to pay. It’s a linked list. What happens when you pay the last debt? What kind of list do you have now? I would think that you have an empty list… otherwise you will owe money to the bank forever.
2 of 18
32
There's no reason to store nothing, but my gosh there absolutely are reasons to represent nothing. This thread is full of them. So the question, then, is how do you want to represent an empty list in your code? How do you signal to the program that sometimes there is a list here, and right now, it's empty? You seem to currently want to represent this empty condition external to the list, by creating and freeing the list on-demand. But consider: now every bit of code you have that has to add something to the list has to first check if there even is a list, and create one if there isn't. And every bit of code that removes something from the list has to check if it's the last element, and free the list if it is. People here are suggesting instead to move your representation of an empty list inside the list. Whatever function or bit of code you hopefully re-use to add or remove items from the list can handle this emptiness internally, so any code that uses your list can ignore this fiddly detail. Which one will be a nicer interface will depend on your code, but there's a reason everybody here is suggesting the second one. In almost all situations it makes reading and writing code easier and less error prone.
🌐
Stack Overflow
stackoverflow.com › questions › 34969717 › checking-if-a-linked-list-is-empty-in-c
Checking if a Linked list is Empty in C - Stack Overflow
You might be lucky and by pure chance your implementation of malloc() might be returning zeroed memory (mainly because it hasn't been used for anything else, yet), but you can't afford to rely on that. – Jonathan Leffler Commented Jan 23, 2016 at 22:39 · Are you sure this compiled correctly? It doesn't for me and I get noticeable errors. Which compiler did you use? ... @Rob: it'll compile if you use a C++-ish compiler, but you're right — the structure definition can't be compiled in pure C because there is no type name List until after the typedef is complete.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 31255026 › checking-whether-a-linked-list-is-empty-in-c
Checking whether a linked list is empty in C++ - Stack Overflow
Which can lead to ambiguities: ... is represented with a null pointer, and so emptiness can be detected by the head of the list being the end - i.e being a nullptr....
🌐
Learn C
learn-c.org › en › Linked_lists
Linked lists - Learn C - Free Interactive C Tutorial
A linked list is held using a local pointer variable which points to the first item of the list. If that pointer is also NULL, then the list is considered to be empty.
🌐
Stack Overflow
stackoverflow.com › questions › 19805569 › how-to-check-if-a-certain-linked-list-in-an-array-of-linked-lists-is-empty
c++ - how to check if a certain linked list in an array of linked lists is empty - Stack Overflow
Why not just check if ( hashTable[index].empty() ) {...} ... sorry, i forgot to explain that the hash function is the hf(word) [which takes the word and turns it into an integer to be indexed] hash is an object of HashTable (which was defined in a .h file) ... I suppose the question I am asking would be; How can I check if the first element of a linked list is empty in an array of linked lists.
🌐
Vaia
vaia.com › all textbooks › computer science › starting out with c++: early objects › chapter 17 › problem 3
Problem 3 To indicate that a linked list i... [FREE SOLUTION] | Vaia
For instance, in C/C++, you use 'NULL', while in Python, the word 'None' is used. This special value informs the program that there are no nodes for the linked list to process. Checking against `NULL` or `None` helps efficiently determine if ...
🌐
Cplusplus
cplusplus.com › forum › general › 126091
Empty Linked List - C++ Forum
Hi, I've got an assignment where we have to start out with an empty linked list that is formatted as IntNode* head = NULL; Every time I attempt to run it, it goes to that line and then the program stops working. Any ideas? I'll include the rest of the code below.
🌐
Quora
quora.com › How-can-you-check-if-a-linked-list-has-null-values-without-calling-its-size-function
How to check if a linked list has null values without calling its size() function - Quora
In your code for example, you may iterate through the list until if(element->next == NULL) returns TRUE which means you are at the last element. Here is a diagram which can describe a very basic singly linked list with exactly 3 entries in the list:
🌐
Delft Stack
delftstack.com › home › howto › cpp › cpp check if linked list is empty
How to Check if Linked List Is Empty in C++ | Delft Stack
February 2, 2024 - In C++, there’re two primary ways to check if a linked list is empty either by providing a pointer to the first element of a list (for example: if (root->next == NULL) { /* empty list */ }) or by link back the list element of a linked list ...
🌐
w3resource
w3resource.com › cpp-exercises › stack › cpp-stack-exercise-17.php
C++ Check the size and empty status of a stack (linked list)
<< endl; // Display message if ... // Move to the next node } cout << endl; } // Function to check if the stack is empty bool isEmpty() { return (top == NULL); // Return true if the top pointer is NULL, else false } // Function ...
🌐
Maixiangyuan
maixiangyuan.ca › post › how-to-check-if-a-list-is-empty-c
how to check if a list is empty c
January 18, 2025 - Determining whether a list is empty in C requires different approaches depending on whether you're using an array or a linked list. Using a size variable for arrays and checking the head pointer for linked lists provides the most reliable and ...