0

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?

asked Mar 20, 2017 at 14:38

2 Answers 2

1

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).

answered Mar 20, 2017 at 14:47
Sign up to request clarification or add additional context in comments.

Comments

0

At the second block of code, you don't set the link from the last element to point to the newly inserted element.

answered Mar 20, 2017 at 14:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.