I have two fields namely ID and name. Upon inserting a node in a linked list, I would like to sort it by ID in descending order. Assuming that it is possible that different persons can have the same ID. For Example
1001 CHARICE -> 1001 JUSTIN -> 1001 ANNA -> 1000 CHYNA -> 888 MIKEY -> NULL
The final list should look like this:
1001 ANNA -> 1001 CHARICE -> 1001 JUSTINE -> 1000 CHYNA -> 888 MIKEY -> NULL
I sort the names with the same ID in ascending order while the IDs are sorted in descending order. Here is my code:
NODE* insert_std(NODE *head, NODE* std){
NODE *prev, *cur;
if(head==NULL) return std;
cur = head;
while (cur != NULL && std->ID < cur->ID){
prev = cur;
cur = cur->next;
}
if(std->ID == cur->ID){
while (cur != NULL && strcmp(std->name, cur->name)>=0){
prev = cur;
cur = cur->next;
}
}
if (head==cur){
if(std->ID >= head->ID) {
std->next = head;
head = std;
}
} else {
std->next = cur;
prev->next = std;
}
return head;
}
But is is not being sorted the way I want it. What am I doing wrong?
strcmp(or POSIXstrcasecmp).