Podo
Podo

Reputation: 709

Stop peeking at empty stack

I'm checking that a stack is sorted by popping it and comparing the pop to the peek. If the pop is greater than the peek, we know those two elements are in order. I run this loop as long as the stack isn't empty.

The problem I'm running into is with the final element of the stack. I do my final pop, and but it tries to peek at an empty stack to make sure it's in order. Since there is nothing there, I get a runtime error.

public static boolean isSorted(Stack<Integer> s){
boolean result = true;

while(!s.empty()){
    if(s.pop() < s.peek()){
        result = false;
    }
}

return result;
}

I'm trying to do this exclusively with Stack, so using only push pop and peek. Nothing from an ArrayList. How can I fix this problem, while still checking every element?

I've tried storing pop in a temporary variable, but that fixed nothing. Not sure what I was hoping for

Upvotes: 4

Views: 8948

Answers (3)

xiaofeng.li
xiaofeng.li

Reputation: 8587

One way to do it, is to check the size explicitly:

while(s.size() > 1){ // ok, we have enough elements in the stack
    if (s.pop() < s.peek()) {
        result = false;
        break; // no need to proceed, we already know it's not sorted.
    }
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

The problem is that you need two items, but empty() checks for just one item. Once you call pop(), you need to do another empty() call prior to executing a peek():

while(!s.empty()){
    // We know we have one element available; store it in "top"
    Integer top = s.pop();
    // If the next element is not available, exit 
    if (s.empty()) {
        break;
    }
    if(top < s.peek()){
        // Once result is set to "false", it never becomes "true"
        // so we might as well return now:
        return false;
    }
}
return true;

Upvotes: 5

Shady Atef
Shady Atef

Reputation: 2401

It has to, as pop removes the last element and peek throws EmptyStackException if the stack is empty

public static boolean isSorted(Stack<Integer> s){
boolean result = true;
while(!s.empty()){
    if(s.size() == 1)
        return result;
    if(s.pop() < s.peek()){
        result = false;
    }
}

return result;
}

Upvotes: 0

Related Questions