Hey,
I have a code that works fine, but I have a question about efficiency.
Here is a snippet of my code
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).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; }
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!



LinkBack URL
About LinkBacks


