In a simple C implementation of Linked List, I was unable to define a function string named insert (). It takes a char and adds to the linked list in alphabetical order. A line about creating a new node when the list is empty. And since there will be only one node in the list, the line should look like Ive commented out, am I mistaken?
void insert( ListNodePtr *sPtr, char value ){
ListNodePtr newPtr;
ListNodePtr previousPtr;
ListNodePtr currentPtr;
newPtr = malloc( sizeof( ListNode) );
if( newPtr != NULL ){
newPtr->data = value;
newPtr->nextPtr = NULL;
previousPtr = NULL;
currentPtr = *sPtr;
while( currentPtr != NULL && value > currentPtr->data ){
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
if( previousPtr == NULL ){
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else{
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else
printf( "%c not inserted. No memory available.\n", value);
}
typedef commands in main ():
typedef struct listNode ListNode;
typedef ListNode* ListNodePtr;
and the insert () function is called in main () as follows:
insert( &startPtr, item);
initialization startPointer in main ();
ListNodePtr startPtr = NULL;
source
share