0

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?

3

3 Answers 3

2

In your insertion function, whenever you compare two nodes, compare the two IDs first. If one is smaller than the other, this tells you which node should come first. If the IDs are the same, you need to compare the names to decide which node comes first.

This amounts to modifying std->ID <= cur->ID and std->ID > head->ID. If I were you, I would write a helper function that would take two pointers to NODE (call them A and B), compare them in the manner described above and return true if node A comes before node B. Incorporating this function into your insert_std is then trivial.

Sign up to request clarification or add additional context in comments.

Comments

2

Simply replace your comparisons on ID values, and take into account the name as well (for example using strcmp) when the ID values are the same. The easiest way is to write a separate function for comparing two records which does this job.

Comments

0

Add && std->ID == cur->ID on the while loop

 while (cur != NULL &&  std->ID == cur->ID && strcmp(std->name, cur->name)>=0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.