Adarsh Mohanty
Adarsh Mohanty

Reputation: 11

singly linked list insertion issue

I was trying to insert element at end of a linked list, but if I comment the break in my while loop, it goes to a continuous loop, I'm unable to figure out why

code:

head=NULL;
node *temp=head;

for(int i=0;i<5;i++)
{
    //temp=head;
    node* t1=new node;
        
    if(head==NULL)
    {
        t1->a=i;
        t1->next=NULL;
        head=t1;
    }
    else
    {
        temp=head;
        while(temp!=NULL)
        {
            if(temp->next==NULL)
            {
                t1->a=i;
                t1->next=NULL;
                temp->next=t1;
                //break;
            }
            temp=temp->next;
        }
    }
}

temp=head;
while(temp!=NULL)
{
    cout<<temp->a<<endl;
    temp=temp->next;
} 

Upvotes: 0

Views: 66

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596287

Your while loop runs forever without the break because temp is never set to NULL to stop the loop. When the while loop reaches the last node in the list, it appends the new node to the end, then sets temp to that node. So the next loop iteration sees that node, appends again, and again, and again, endlessly.

So, you need to break the while loop when the last node has been reached:

for(int i = 0; i < 5; i++)
{
    node* t1 = new node;
    t1->a = i;
    t1->next = NULL;

    if (head == NULL)
    {
        head = t1;
    }
    else
    {
        node *temp = head;
        while (temp != NULL)
        {
            if (temp->next == NULL)
            {
                temp->next = t1;
                break;
            }
            temp = temp->next;
        }
    }
}

In which case, the while loop can be simplified to not need break at all:

for(int i = 0; i < 5; i++)
{
    node* t1 = new node;
    t1->a = i;
    t1->next = NULL;

    if (head == NULL)
    {
        head = t1;
    }
    else
    {
        node *temp = head;
        while (temp->next != NULL)
        {
            temp = temp->next;
        }
        temp->next = t1;
    }
}

That being said, this whole code can be greatly simplified further, to not reiterate the entire list on each iteration of the outer for loop, and to not use an if.. else to decide whether or not to set the head:

node **temp = &head;
while (*temp != NULL)
{
    temp = &((*temp)->next);
}

for(int i = 0; i < 5; i++)
{
    node* t1 = new node;
    t1->a = i;
    t1->next = NULL;

    *temp = t1;
    temp = &(t1->next);
}

Upvotes: 0

ObliteratedJillo
ObliteratedJillo

Reputation: 5166

Your while loop is trying to traverse the new node you have just added again and again. Breaking the loop after the insert operation is correct here, otherwise the while loop may loop indefinitely.

Upvotes: 1

Related Questions