C++ exercises and solutions: min max items of Stack


Stack

Min and Max items of Stack


Step 5: Showing the minimum and maximum items

To find the minimum item of the Stack, 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 *t=pfirst;
ListElem *min=pfirst;
while (t != NULL)
{
if (t->data<min->data) { min=t;}
t = t->next;
}

return min;

}

Finding the maximum item of the Stack 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 *t=pfirst;
ListElem *max=pfirst;
while (t != NULL)
{
  if (t->data>max->data) { max=t;}
  t = t->next;
}

return max;

}




Comments

@artlavish26 comment

 @artlavish26

these website was very useful


2016-01-27



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.