In the linked list when we perform insertLast(int item) function, we do the following steps:
struct node *temp;
struct node *newItem;
newItem = (struct node*)malloc(sizeof(struct node));
temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newItem;
newItem->next = NULL;
But if we do:
struct node *temp;
struct node *newItem;
newItem = (struct node*)malloc(sizeof(struct node));
temp = head;
while(temp != NULL){
temp = temp->next;
}
temp = newItem;
newItem->next = NULL;
we get an error, why does this happen?
2 Answers 2
The loop
while(temp != NULL){
...
}
will terminate with temp == NULL
, that is after running past the end of the list. Then
temp = newItem;
assigns a pointer to a newly created object to the temp
variable – but that has nothing to do with a list anymore.
Hence there is no reason for any 'error' (except that the new item does not get appended to a list).
Comments
At the second block of code, you don't set the link from the last element to point to the newly inserted element.