Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

WRITE C++ CODE You have been provided with a linked list of several nodes, each

ID: 3919354 • Letter: W

Question

WRITE C++ CODE

You have been provided with a linked list of several nodes, each containing two types of data: a name of type string, and a grade of type double.

First, display the list to the user as is (this is already finished for you).

Then, using any method of your choice (push onto stacks, put into vectors or arrays and sort via bubble, binary, etc.) EXCEPT explicitly reordering the linked list itself (i.e. change the order in which the nodes point; that would be too easy!), reorder and display the linked list (display both name and grade) to the user in:

1. Alphabetical order, by name

2. Descending order (highest to lowest), by grade

Explanation / Answer

Sorting by Selection Sort is as follows:

node *sortByName(node *start){

     if (start != NULL){

          node *p = start;
          while(p != NULL){
              node *q = p->next;
              node *minptr = p;
              while(q != NULL){
                  if (minptr->name > q->name){
                     minptr = q;
                  }
                  q = q->next;
              }
              string tempn = p->name;
              double tempg = p->grade;
              p->name = minptr->name;
              p->grade = minptr->grade;
              minptr->name = tempn;
              minptr->grade = tempg;
              p = p->next;
          }
     }
     display(start)
     return start;

}


node *sortByGrade(node *start){

     if (start != NULL){

          node *p = start;
          while(p != NULL){
              node *q = p->next;
              node *maxptr = p;
              while(q != NULL){
                  if (maxptr->grade < q->grade){
                     maxptr = q;
                  }
                  q = q->next;
              }
              string tempn = p->name;
              string tempg = p->grade;
              p->name = maxptr->name;
              p->grade = maxptr->grade;
              maxptr->name = tempn;
              maxptr->grade = tempg;
              p = p->next;
          }
     }
     display(start);
     return start;

}


For displaying the list we have:

void display(node *start){
    node *p = start;
    if (start != NULL){
       while (p != NULL){
           cout << p->name << " " << p->grade << endl;
           p = p->next;
       }
    }
}