Thanks for the answers from r sahu and janos for reviewing the code, as i have refactored the code as per their comments , still both of the answers answers the real question.
Here is the edited / updated code ,
#include <stdio.h>
#include <stdlib.h>
/* A linked list node */
typedef struct sList
{
void *data;
struct sList *nextNode;
}sList;
//Function prototypes */
sList *newNode(void);
void unitTestLinkedList(void);
void displaySList(sList *psList);
sList *addNodeToHead(sList *psList,void *data);
int main(int argc,char *argv[])
{
unitTestLinkedList();
return 0;
}
sList *addNodeToHead(sList *psList,void *data)
{
sList *psListNew = newNode(data);
if(psListNew == NULL)
{
printf("DEBUG : Node not created succesfully !\n");
return NULL;
}
psListNew->nextNode = psList;
return psListNew;
}
sList *newNode(void *data)
{
sList *psList = (sList *) malloc(sizeof(sList));
if(psList == NULL)
{
printf("DEBUG :New Node not created succesfully !\n");
return NULL;
}
psList->data = data;
psList->nextNode = NULL;
return psList;
}
void displaySList(sList *psList)
{
if(psList == NULL)
printf("DEBUG : List is empty !!!\n");
else
{
while(psList != NULL)
{
printf("Data = %d \n", psList->data);
psList = psList->nextNode;
}
}
}
void unitTestLinkedList(void)
{
sList *psList = NULL;
int numbers[10] = {1,2,3,4,5,6,7,8,9,10};
//Test for empty list
displaySList(psList);
psList = addNodeToHead(psList,(int *)numbers[9]);
psList = addNodeToHead(psList,(int *)numbers[8]);
psList = addNodeToHead(psList,(int *)numbers[7]);
psList = addNodeToHead(psList,(int *)numbers[6]);
psList = addNodeToHead(psList,(int *)numbers[5]);
//Test in middle
displaySList(psList);
psList = addNodeToHead(psList,(int *)numbers[4]);
psList = addNodeToHead(psList,(int *)numbers[3]);
psList = addNodeToHead(psList,(int *)numbers[2]);
psList = addNodeToHead(psList,(int *)numbers[1]);
psList = addNodeToHead(psList,(int *)numbers[0]);
//Test at end
displaySList(psList);
}
To update nodes count or count nodes we can have a separate function to handle that or we can have a list container to update count , head , tail or what ever needed .
typedef struct slistInfo
{
sList *psListHead;
sList *psListTail;
unsigned int sListNodeCount;
}
We can update the above List every iteration of addNodeToHead
unsigned int sListNodeCount = 0;
we can update the above integer (global) through a separate function call
unsigned int sListCount(sList *psList)
{
while(psList != NULL)
{
++sListNodeCount ;
psList = psList->nextNode;
}
return sListNodeCount;
}