Hey,
I have a code that works fine, but I have a question about efficiency.
Here is a snippet of my code
Code:
void insert_at_end ( listNode * ptr, int data )
{
listNode temp;
temp=*ptr;
if(*ptr==NULL)
{
temp=malloc(sizeof(lNode));
temp->n=data;
temp->next=NULL;
*ptr=temp;
return;
}
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=malloc(sizeof(lNode));
temp->next->n=data;
temp->next->next=NULL;
temp=temp->next;
}
What this does it gets the head of the linked list, goes until the end, and then tacks on another node. I noticed that this has O(N) complexity, and will be super inefficient if I have a large list(like a billion nodes or something).
Is there a more efficient way of adding at the end, WITHOUT using a tail pointer? I know it could be done in O(1) time with a tail pointer, but I'm not sure I'll be able to use tail pointers in labs and such.
Thanks!
Thanks!