#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void insert( struct node *q,int num)
{
struct node *temp;
if( q == NULL)
{
q = (struct node*)malloc(sizeof(struct node));
q->data = num;
q->next = NULL;
}
else
{
temp = q;
while( temp != NULL)
{
temp = temp->next;
}
temp = (struct node*)malloc(sizeof(struct node));
temp->data = num;
temp->next = NULL;
}
}
void display(struct node *q)
{
struct node *temp;
temp = q;
while(temp != NULL)
{
printf("%d",temp->data);
temp = temp->next;
}
}
int main()
{
struct node *a;
a = NULL;
insert( a,13);
insert( a,13);
display(a);
return 0;
}
In the insert function q is a pointer to struct node which is initialized to NULL.
Here I am seeing 1st if q is NULL or not. If it is null then I am allocating heap memory, data and next pointer, in this way q is now a pointer which is dereferencing to 1st data. If q is not NULL, then I take a temp pointer which points to a struct node which is being pointed by q, so till temp becomes NULL temp goes to temp->next, then it allocates heap memory, puts data and next pointer to NULL.
But it is showing nothing for my display function please correct me on this, and on how stack and heap memory is used in linked list.
Recall that in C arguments are pass-by-value, including pointer arguments.
When
q == NULL, you’re allocating memory and assigning that memory toq, but this won’t changeqoutside your function: only the copy ofqinside your function will be changed.In order to change what the argument
qpoints to, and have those changes reflected outside your function, you’ll need to pass a pointer to a pointer, e.g.:And change how you’re using
q, e.g.Furthermore, in your else case, you should loop until
temp->next == NULL, then add your new node with: