Home > Software design >  Finding the max element in a stack
Finding the max element in a stack

Time:09-29

I have my first assignment using a Stack Class that uses a dynamically allocated array to store data values, and I am confused trying to find the max and min elements of the stack. I was given the header file for the class Stack, which has the functions, Empty, Full, Top, Push, Pop, Size, Max, Min, and Peek. Can I have some advice on how to properly get the Max of a stack?

Here is what I have so far:

int Stack :: Max(){

    if (Empty()){
        throw EmptyStack();
    }
    int max = array[top];
    int next;

    while (!Empty()){
        next = array[top];
    }
    if (max < next){
        max = next;
    }
    return max;
}

CodePudding user response:

Your while loop runs endlessly, as it never removes elements from the array to cause the !Empty() condition to ever evaluate as false. And, it doesn't modify top, so it is always evaluating the same element over and over.

Since you clearly have direct access to the array, just iterate through it normally. Try something more like this instead (assuming the stack indexes the array elements from top down to 0):

int Stack :: Max(){

    if (Empty()){
        throw EmptyStack();
    }

    int max = array[top];

    for (int i = top-1; i >= 0; --i){
        int next = array[i];
        if (next > max){
            max = next;
        }
    }

    return max;
}

And then you can do the same thing for Min(), just using if (next < min) instead.

CodePudding user response:

You are only checking the last value against the first value of the stack. Instead you would want to check all the values inside the stack and find the max value. Just put your if inside the while statement.

int Stack :: Max(){

    if (IsEmpty()){
        throw EmptyStack();
    }
    int max = array[top];
    int next;

    while (!Empty()){
        next = array[top];
        if (max < next){
            max = next;
        }
    }
    return max;
}
  •  Tags:  
  • c
  • Related