Inserting to sorted linked list
Hi all.
Been a long time since I posted here and I'm a bit rusty with my C.
I'm trying to write a function that inserts into a linked list where node->name is in alphabetical order.
This is what I have so far and it seems logical to me but I just can't understand why they are not sorted.
Code:
void insertProductNode(char *brand, char *name, unsigned price, unsigned qty, ProductNodeType **head){
ProductNodeType *node = malloc( sizeof(ProductNodeType) );
ProductNodeType *iter = *head;
if( node == NULL ){
fprintf(stderr, "Error allocating memory. addProductNode()");
exit(EXIT_FAILURE);
}
strncpy( node->brand, brand, PRODUCT_BRAND_MAX );
strncpy( node->name, name, PRODUCT_NAME_MAX );
node->qty = qty;
node->price = price;
node->nextProduct = NULL;
if( iter == NULL ){
*head = node;
}
else{
while( iter != NULL ){
if( iter->nextProduct == NULL ){
iter->nextProduct = node;
break;
}
else if ( strcmp( node->name, iter->name ) < 0){
node->nextProduct = iter->nextProduct;
iter->nextProduct = node;
break;
}
iter = iter->nextProduct;
}
}
}
Code:
typedef struct productNode
{
char name[PRODUCT_NAME_MAX + 1];
char brand[PRODUCT_BRAND_MAX + 1];
unsigned price;
unsigned qty;
struct productNode* nextProduct;
} ProductNodeType;