Click here to Skip to main content
15,867,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I had written this function for inserting aa node at front of linked list. According to me this code should work but its not.

C++
struct node* insert_back(struct node*& head, int data){
	struct node* p = head;
	while(p!= NULL){
		p = p->next;
	}
	struct node* new_node = (struct node*)malloc(sizeof(node));
	new_node->data = data;
	new_node->next = NULL;
	p  = new_node;
	return head;
}
Posted

1 solution

Your code creates a new node, setting p to point to it, but not adding it into the list anywhere. You then return head to the caller, at which point p goes out of scope and is lost. You can verify this quite easily by using the debugger to step through the code.
 
Share this answer
 
v3
Comments
CPallini 9-Jun-15 6:10am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900