Hi,
I have this code fragment that is suppose to find the max value in a queue. It seemed to work fine until I switched up the locations of the letters being fed into the queue.
It is suppose to compare each element of the queue and return the largest number/letter.

somehow it seems like it might be just comparing the first and last queue location and I dont understand why . Can anybody tell me what's wrong with the code .

//**************************************************************************
//SomeType Max() const;
// Max()
// Returns largest data value found within queue WITHOUT 
//modifying the queue.  
// Throws EmptyQueue if queue is empty
//**********************************************************************
SomeType Queue:: Max() const {
if(IsEmpty()){
    throw EmptyQueue();
}
QueueNode* tempPtr;
SomeType tempValue;

tempPtr=frontPtr;


while((tempPtr)!=NULL){
tempValue=tempPtr->data;
  if(tempValue<(tempPtr->data))
    {
     tempValue=tempPtr->data;
    }
tempPtr=tempPtr->nextPtr;
}
delete tempPtr;
return tempValue;

}

try moving line 19 to line 17 so you don't assign tempPtr->data to tempValue each time through the loop. You only want to do that if the value of the conditional in the if statement is true.

thank you for your response
I tried what you said but its giving me a segmentation fault :(

Debug the code and find out why? If you aren't familiar with using debugging software then put temporary code in to output the value of tempValue and tempPtr->data after initial assignment of tempPtr->data outside the loop and each time through the loop with code to pause the program so you can view the output each time.

Also, tempPtr is not declared using dynamic memory so why are you trying to delete as if it were?

Debug the code and find out why? If you aren't familiar with using debugging software then put temporary code in to output the value of tempValue and tempPtr->data after initial assignment of tempPtr->data outside the loop and each time through the loop with code to pause the program so you can view the output each time.

Also, tempPtr is not declared using dynamic memory so why are you trying to delete as if it were?

ok i see what you mean about the tempPtr...i am on unix and i'm not familiar with using debugging software

This article has been dead for over six months. Start a new discussion instead.