﻿ C++ exercises solutions: min and max items of linked list

# C++ exercises solutions: min and max items of linked list

### Min and max items of circularly linked list

Step 5: Showing the minimum and maximum items

To find the minimum item of the circularly linked list, you need to compare each item of the list by allowing a min variable to point to the first item of the list then starting to compare its data with its next item. If the data of its next item is less than the data of the min, simply allow the min to catch the next item.

//Find min item

ListElem *findmin(ListElem *L){
ListElem *min,*tr;
min=L;

if(L!=NULL){
tr=L->next;
while(tr!=pfirst){
if(tr->data<min->data) min=tr;
tr=tr->next;
}
return min;
}
else return NULL;//empty list

}

Find the maximum item of the circularly linked list can be done similarly as finding the minimum item. You need to compare each item of the list by allowing a max variable to point to the first item of the list then starting to compare its data with its next item. If the data of its next item is greater than the data of the max, simply allow the max to catch the next item.

//Find max item
ListElem *findmax(ListElem *L){
ListElem *max,*tr;
max=L;

if(L!=NULL){
tr=L->next;
while(tr!=pfirst){
if(tr->data>max->data) max=tr;
tr=tr->next;
}
return max;
}
else return NULL;//empty list

}