and here i've shortended to code even more, i guess it's easier to understand:
Code:for (prev=NULL; loc != NULL; loc = loc->next) { prev = loc; } prev->next = temp;
and here i've shortended to code even more, i guess it's easier to understand:
Code:for (prev=NULL; loc != NULL; loc = loc->next) { prev = loc; } prev->next = temp;
check for loc->next is not equal to nullOriginally Posted by Axel
ssharish2005
noo. the reason why i said, when u interate through each node u will check for the last node.The way u can find is that the last node next should be null. So when u check for loc->next is equal to null u will come to know that u reached end of the node. and then u can follow with appending a new node.
ssharish2005
Last edited by ssharish2005; 10-14-2006 at 04:26 AM.
this is not quite rite ...Originally Posted by Axel
say u haveon the first iteration, loc = *start yes?Code:"Panda" -> NULL
and then you assign prev to loc...
and after that, the for loop checks the nullity of locCode:prev = loc;
.. in this case, no... and then loc goes to the next element which is null...Code:for (prev=NULL; loc != NULL; loc = loc->next)
which is a problem because after thatCode:for(..., loc = loc->next)
remember in linked list, the last element isn't denoted by NULL... it's denoted by the last item BEFORE NULLCode:prev = loc; // prev becomes null (but we don't want it to be)
NULL is just like '\0' character in string.
got me? this is exactly what ss was saying
Last edited by yxunomei; 10-14-2006 at 04:41 AM.
ok i think i've understood my original code now please correct me if i'm wrong.
We have the first element, Cat already added so:
evaluates to false so we go to the else bit.Code:if (*start == NULL)
Code:else { loc = *start; // MAKE loc point to the start of the list. prev = NULL; for (i=0; loc != NULL; i++) //here we just loop till we find an empty position to append to { prev = loc; // keep track of the previous node by copying what the current node equals to loc = loc->next; // set loc to the next node }Code:once the loop ends it means we have found an empty position i.e.: [ CAT ] [ NULL ] prev loc so: prev->next = temp; we just insert the new node AFTER prev->next i.e.: [ CAT ] [ DOG (new node inserted) ] prev - > next
i don't see why you need the i injust do something likeCode:for (i=0; loc != NULL; i++)this, not only you make it easier to understand, but also make your code shorter because then you can take out theCode:for(loc = *start; loc != NULL; loc = loc -> next)at the start of the else bit.Code:loc = *start
better yet
Code:for(loc = *start; loc->next != NULL; loc = loc->next) { // do nothing, it's all done in the loop } loc->next = temp;
Last edited by yxunomei; 10-14-2006 at 04:40 AM.