﻿ C# exercise solutions-min max items of Queue

C# OOP: Queue

Min and Max items of Queue

Step 5: Showing the minimum and maximum items

To find the minimum item of the Queue, 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 the min item of the Queue
public ListNode<T> findmin()
{
ListNode<T> t, min;
t = pfirst;
min = t;
while (t != null)
{
if (t.val.ToString().CompareTo(min.val.ToString()) < 0) min = t;
t = t.next;
}

return min;
}

Find the maximum item of the Queue 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 the max item of the Queue
public ListNode<T> findmax()
{
ListNode<T> t, max;
t = pfirst;
max = t;
while (t != null)
{
if (t.val.ToString().CompareTo(max.val.ToString()) > 0) max = t;
t = t.next;
}

return max;
}

}