coolguysyndrome
coolguysyndrome

Reputation: 15

Is this a way to check whether or not a LinkedList node is initialized?

I am trying to create an insert-at-end function for a linked list class. I was having some trouble, so I looked up some code and found the following:

if (!start) // empty list becomes the new node
{
    start = newNode;
    return;
}

This seems to be a check to make sure that if the user uses the function with an empty list, the newly created "ending" node, newNode, becomes the start node. But, what does if (!start) do? (start is the head node).

Upvotes: 0

Views: 504

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595971

A linked list is implemented as a chain of pointers to node objects.

Empty

---------
| start | -> nullptr
---------

1 node

---------    ---------
| start | -> | value |
---------    ---------
             | next  | -> nullptr
             ---------

2 nodes

---------    ---------      ---------
| start | -> | value |  |-> | value |
---------    ---------  |   ---------
             | next  | -|   | next  | -> nullptr
             ---------      ---------

And so on...

The expression if (!start) is checking whether the start pointer is null, which it should be if the list is empty. The expression is equivalent to if (start == nullptr) when checking a pointer.

Assuming a single-linked list, then chances are that your function is likely implemented roughly similar to the following:

void insertAtEnd(T value)
{
    node *newNode = new node;
    newNode->value = value;
    newNode->next = nullptr;

    if (!start) // if (start == nullptr)
    {
        start = newNode;
        return;
    }

    node *n = start;
    while (n->next) // while (n->next != nullptr)
    {
        n = n->next;
    }

    n->next = newNode;
}

A simpler and preferred way to implement this function would look more like the following:

void insertAtEnd(T value)
{
    node **n = &start;
    while (*n) // while (*n != nullptr) 
    {
        n = &((*n)->next);
    }

    *n = new node;
    (*n)->value = value;
    (*n)->next = nullptr;
}

Upvotes: 2

rootkonda
rootkonda

Reputation: 1743

if (!start) // empty list becomes the new node
{
    start = newNode;
    return;
}

! negates whats in start. So if start is NULL then !NULL meaning true so it goes inside and make it as a start node. Similarly when start is not NULL then it doesn't go inside.

Upvotes: 2

Related Questions