I'm trying to figure out how to insert a node into a linked list at a particular location based on a time and am confused. Any suggestions or help would be appreciated.
I have this declared outside of everything globally.
Code:
struct aTime {
char name[LENGTH];
int time;
struct aTime* next;
};
struct aTime* head = NULL;
And then this function that is used to add nodes (aTime structs) to a linked list. It adds the first node fine, but not subsequent ones. I think this is because I have while p-> != NULL but it is always going to be null when the function is called since I create a new aTime struct. So I guess my question is how, after one struct has been added at the beginning, do I point to the head node and traverse the list, insert a node, and make sure everything is still linked? Do I need another temp aTime struct?
Code:
void add_time(char name[LENGTH], int seconds)
{
struct aTime *p;
p = (struct aTime *) malloc(sizeof(struct aTime));
if (head == NULL)
{
strcpy(p->name, name);
p->seconds = seconds;
p->next = list_head;
list_head = p;
return;
}
else
{
while (p->next != NULL)
{
if (p->seconds < seconds)
{
strcpy(p->name, name);
p->seconds = seconds;
return;
}
else
{
p = p->next;
}
}
}
}
Thanks for any help or suggestions.