This is my code to add node at beginning.
void screate(ll *node)
{
ll *newNode=(ll *)malloc(sizeof(ll));
printf("Enter number :\t");
scanf("%d",&newNode->data);
if(newNode->data != NULL)
{
newNode->next=node;
node= newNode;
screate(node);
}
else
{
free(newNode);
newNode=NULL;
}
}
Even i found same code here, I unable to figure out, why I getting wrong output.
This is the current node
56->78->77->NULL
But, when i’m trying to add new node at the beginning, then still I’m getting same output i.e. 56->78->77->NULL. Need Help !!
UPDATE
void show(ll *node){
while(node->next != NULL)
{
printf("%d->",node->data);
node=node->next;
}
printf("NULL");
}
You’re assigning to
nodewhich is just a parameter to the function. Since it’s passed by value, this won’t update the version held by the calling function.You need to pass a pointer to it instead (i.e.
ll **node) and change your code to assign to*node, and also changer the caller to add a&before the argument to take its address.If you pass a pointer to something to a function, it can change the something but not the pointer itself. The natural conclusion is therefore to make the something itself the pointer – i.e. a pointer to a pointer.
In principle you can take this pointer chaining as deep as you like, but in practice you won’t generally need anything more than “pointer to pointer to thing”.
Couple of other points. Try to avoid variable names like
landllas lowercase L’s can easily be confused with the digit 1 (and an uppercase I) in many fonts. Also, your use of a recursive call intoscreate()again would be potentially more efficient as awhileloop instead. Some compilers will spot that it’s tail-recursive and optimise to a loop anyway, but I never like to rely on that sort of thing when it’s just as clear to use a loop in the first place.