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

I have the following function of a linked list program below, and it accepts the

ID: 3671514 • Letter: I

Question

I have the following function of a linked list program below, and it accepts the name and age from the user. However, I am looking to arrange the age in ascending order, how do Ii go about this in C++

void insert(node *&head, node *&last,string name, int age)
{
if (isEmpty(head))
  insertAsFirstElement(head, last, name, age);
else
{
  node *temp = new node;
  temp-> name = name;
  temp-> age = age;
  temp-> next = NULL;
  node *temp = NULL;
        temp = head;
  last->next = temp;
  last = temp;
}
}

Explanation / Answer

void insert(node *&head, node *&last,string name, int age)
{
if (isEmpty(head))
insertAsFirstElement(head, last, name, age);
else
{
node *temp = new node;
temp-> name = name;
temp-> age = age;
temp-> next = NULL;


node *iter = head;
node *prev = NULL;
while(iter != NULL && iter->age < age){
   prev = iter;
   iter = iter->next;
}

if(iter == NULL){
   last->next = temp;
   last = temp;
}
else{
       prev->next = temp;
       temp->next = iter;
}

}
}