In a simple Linked List implementation on C, I couldn’t figure out a line of function named insert(). It takes a char and add to the linked list in alphabetical order. The line is about creating a new node when the list is empty. And since there will be only one node on the list, the line should be like I’ve commented, am I wrong?
/****************************************************/
void insert( ListNodePtr *sPtr, char value ){
ListNodePtr newPtr;
ListNodePtr previousPtr;
ListNodePtr currentPtr;
newPtr = malloc( sizeof( ListNode) );
if( newPtr != NULL ){ //is space available
newPtr->data = value; //place value in node
newPtr->nextPtr = NULL; //node does not link to another node
previousPtr = NULL;
currentPtr = *sPtr; //indirection to startPtr
while( currentPtr != NULL && value > currentPtr->data ){
previousPtr = currentPtr; //walk to ...
currentPtr = currentPtr->nextPtr; //... next node
}
//insert new node at the beginning of the list
if( previousPtr == NULL ){
newPtr->nextPtr = *sPtr; /////////////////////////////////////////////// newPtr->nextPtr = NULL ???
*sPtr = newPtr;
}
else{ //insert new node between previousPtr and currentPtr
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else
printf( "%c not inserted. No memory available.\n", value);
}//end-of insert
/*******************************************************/
the typedef instructions in main() are;
typedef struct listNode ListNode;
typedef ListNode* ListNodePtr;
and the function insert() is called in main() like this;
insert( &startPtr, item);
initialization of startPointer in main();
ListNodePtr startPtr = NULL;