A complete program to create a linked list, counting number of nodes, adding new node at the end and reversing the list is as follows:
#include< stdio .h>
#include<alloc . h>
#include<alloc . h>
/* structure containing a data part and link part */
struct node
{
int data ;
struct node *link ;
} ;
void append ( struct node **, int ) ;
void reverse ( struct node ** ) ;
void display ( struct node * ) ;
int count ( struct node * ) ;
void main( )
{
struct node *p ;
int n;
p = NULL ; /* empty linked list */
printf ( "\nNo. of elements in the linked list = %d", count ( p ) ) ;
printf("\n Enter the element you want to insert");
scanf("%d",&n);
append (&p,n);
display ( p ) ;
printf ( "\nNo. of elements in the linked list = %d", count ( p ) ) ;
reverse ( &p ) ;
printf("\n Elements after reversing the linked list\n");
display (p);
}
/* adds a node at the end of a linked list */
void append ( struct node **q, int num )
{
struct node *temp, *r ;
if ( *q == NULL ) /* if the list is empty, create first node */
{
temp = malloc ( sizeof ( struct node ) ) ;
temp -> data = num ;
temp -> link = NULL ;
*q = temp ;
}
else
{
}
}
return(1+count(list->next));
}
/* displays the contents of the linked list */
void display ( struct node *q )
{
printf ( "\n" ) ;
/* traverse the entire linked list */
while ( q != NULL )
{
printf ( "%d ", q -> data ) ;
q = q -> link ;
}
}