Alright so I am trying to insert nodes into a linked list but also I want them to be sorted right away

I think I got most of it except I am struggling when it comes to inserting it to the middle of the table

``````temp -> price = price;

if((*head) == NULL && (*tail) == NULL)
{
temp->next = NULL;
temp->prev = NULL;
(*tail) = tail;

}

{
temp->prev = NULL;

}
else if (price < (*tail->price))
{
temp->next = NULL;
temp->prev = (*tail);
(*tail)->next = temp;
(*tail)= temp;

}
else
{
while(price < temp->price && temp != NULL)
temp = temp->next;

temp=temp->prev;

//I AM STUCK OVER HERE

}
``````

You need a while loop to find the correct spot. On line 5 just do a return. Then start the while loop to find out where to put the new node, like lines 30-32.

``````temp -> price = price;
if((*head) == NULL && (*tail) == NULL)
{
temp->next = NULL;
temp->prev = NULL;
(*tail) = tail;
return;
}
while(price < temp->price && temp->next != NULL)
temp = temp->next;
// now insert the new node
``````

I am struggling with the while loop. Do I need to malloc an additional node?

my insert function is is also void.

But for this part

``````if((*head) == NULL && (*tail) == NULL)
{
temp->next = NULL;
temp->prev = NULL;
(*tail) = tail;
}
{
temp->prev = NULL;
}
else if (price < (*tail->price))
{
temp->next = NULL;
temp->prev = (*tail);
(*tail)->next = temp;
(*tail)= temp;
}
``````

Is this correct? I believe I am covering if it is the first node in the list, if not then check if the price is bigger then the head, if not then check if the price is smaller then the current tail, then if it is not that either I should insert the node? Or is my logic flawed

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.