Reputation: 3
Below fragment is invalid to inserting a node in the end of Linked List.
void insert_end(int item){
nodeptr newNode = new ListNode;
newNode->data = item;
newNode->next = NULL;
if(head == NULL){
head = newNode;
curr = head;
}else{
curr = head;
while(curr != NULL) curr = curr->next;
curr = newNode;
}
}
Another fragment that is valid to inserting a node in the end of Linked List.
void insert_end(int item){
nodeptr newNode = new ListNode;
newNode->data = item;
newNode->next = NULL;
if(head == NULL){
head = newNode;
curr = head;
}else{
curr = head;
while(curr->next != NULL) curr = curr->next;
curr->next = newNode;
}
}
My question is why 1st one is invalid? Actually two fragments should be similar. Assume i have three nodes already. Now i want to inserting another node.
so can i say first algorithm's 'curr' and second algorithm 'curr->next' both are similar, when "while loop" terminated? if it's not similar then why?
Upvotes: 0
Views: 1147
Reputation: 2392
You must understand a pointer is a variable which value is an address.
First algorithm is wrong because when you finish the iteration of while loop, curr points to NULL (address 0x0), and NULL is not a valid node of your list.
Second algoritm works because when you finish the iteration of while loop, curr points to last node of your list, and you add newNode to curr->next, replacing NULL by the address of newNode.
Hope this helps! :)
Upvotes: 1