I'm trying to do a simple program, adding a node to the end of the link list:
/*Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* Insert(Node *head,int data)
{
if(head){
Node *curr_node=head;
while(curr_node->next)
curr_node=curr_node->next;
}
Node *new_node=(Node *)calloc(1,sizeof(Node));
new_node->data=data;
new_node->next=NULL;
if(head)
curr_node->next=new_node;
else
head=new_node;
return head;
}
/* the main function calls it*/
A variable declared in a function definition has a scope which extends only to the innermost {}
braces. So your variable curr_node
is no longer valid after the first if
block.
To fix this, declare your variable outside the if
block:
Node* Insert(Node *head,int data)
{
Node *curr_node = NULL;
if(head){
curr_node=head;
while(curr_node->next)
curr_node=curr_node->next;
}