C++ Program Write a function called max that takes as input a reference to a sin
ID: 3798919 • Letter: C
Question
C++ Program
Write a function called max that takes as input a reference to a single queue of integers and returns the largest integer in the queue without destroying the queue. That is, the queue you return must be in the same state as when you called the function max. In order to be effecient, your function should not create any copies of the queue. However, you are permitted to modify the queue as you search for the largest element . You may assume that any queue passed to max always has at least one element , so the notion of largest elemet is well defined.
Explanation / Answer
#include <iostream>
#include <stdlib.h>
using namespace std;
//define a node
typedef struct ListNode{
int data; // the element data
struct ListNode *next; // next link
}ListElem;
//define first and last pointers of queue
ListElem *pfirst;
ListElem *plast;
//Find max item
ListElem *findmax(ListElem *pfirst){
ListElem *t=pfirst;
ListElem *max=pfirst;
while (t != NULL)
{
if (t->data>max->data) { max=t;}
t = t->next;
}
return max;
}
//Add item the Queue
void addAtBack (int val)
{
int t;
ListElem *item;//new element to be Added
item=(ListElem *)malloc(sizeof(ListElem)); //allocate space
item->data=val;
//Add a new item to the empty Queue
if(pfirst==NULL && plast==NULL){
//The first and last item point to the new item when they are null--empty Queue.
item->next=NULL;
pfirst=item;
plast=item;
cout<<"Added: "<<item->data<<endl;
}
//Add a new item at the end of the Queue
else
{
item->next = NULL; //The next link of the item is null.
plast->next = item;
plast =item;
cout<<"Added: "<<item->data<<endl;
}
}
int main()
{
cout << "Hello World" << endl;
addAtBack(2);
addAtBack(5);
ListElem *max = findmax(pfirst);
cout << "Max Value: " << max->data << endl;
return 0;
}
========Sample Output=======
Added: 2
Added: 5
Max Value: 5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.