For starters it is a bad idea to declare the global variable i
int i;
You should declare variable in minimal scopes where they are used.
Your function create
does not make a sense.
void create(struct node *head, int n)
{
for (i = 0; i < n; i++)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
scanf("%d", &p->data);
if (head == NULL)
head = p;
else
{
head->ptr = p;
}
}
}
For starters as the pointer to the head node is passed by value to the function then the function deals with a copy of the value of the original pointer. Changing the copy within the function as for example in this statement
head = p;
does not influence on the original pointer in main. It will stay unchanged.
Also there are numerous memory leaks because addresses of the allocated memory for nodes in the loop are being lost because in this statement
head->ptr = p;
they are being overwritten.
The function should do only one thing: add a new node with the specified value to the list. The for loop should be moved in the caller of the function.
The function can look the following way
int create( struct node **head, int data )
{
struct node *p = malloc( sizeof( struct node ) );
int success = p != NULL;
if ( success )
{
p->data = data;
p->ptr = *head;
*head = p;
}
return success;
}
And in main the function can be called for example the following way
struct node *head = NULL;
int n;
scanf( "%d", &n );
int success = 1;
for ( int i = 0; success && i < n; i++ )
{
int data;
scanf( "%d", &data );
success = create( &head, data );
}
Pay attention to that in the function display you are outputting a value stored in the head node
printf("%d", head->data);
you have to write
printf("%d", p->data);
Here is a demonstrative program that shows how new nodes can be added to the list.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct node
{
int data;
struct node *ptr;
};
int create( struct node **head, int data )
{
struct node *p = malloc( sizeof( struct node ) );
int success = p != NULL;
if ( success )
{
p->data = data;
p->ptr = *head;
*head = p;
}
return success;
}
FILE * display( const struct node *head, FILE *fp )
{
for ( ; head != NULL; head = head->ptr )
{
fprintf( fp, "%d -> ", head->data );
}
fputs( "null", fp );
return fp;
}
int main(void)
{
struct node *head = NULL;
size_t n = 0;
printf( "Enter the number of nodes you want to add to the list: " );
scanf( "%zu", &n );
srand( ( unsigned int )time( NULL ) );
int success = 1;
for ( size_t i = 0; success && i < n; i++ )
{
success = create( &head, rand() % ( int )( 2 * n ) );
}
fputc( '\n', display( head, stdout ) );
return 0;
}
The program output might look like
Enter the number of nodes you want to add to the list: 10
11 -> 16 -> 10 -> 18 -> 9 -> 0 -> 8 -> 1 -> 3 -> 18 -> null