Can someone tell me if my solution to 9.1 does some unnecessary work?

#1

So as far as the push operation for problem 9.1, what I have is the following:
public void push(int e) { stack.addFirst(new ElementAndMax(e, (isEmpty() || e >= max()) ? e : max())); }

However, I see that the extra condition is not added in the book’s code. See below:
public void push(Integer x) { // @judge-exclude-display elementWithCachedMax.addFirst( new ElementWithCachedMax(x, Math.max(x, empty() ? x : max()))); // @judge-include-display }
Why is that? Let’s say you push 2, 5, 4 to the stack. Well, in this case both the top element of the stack and the maximum item in the stack would be found to be 4, in which case the latter is not true.

Am I missing something?

0 Likes

#2

Hah. I see the answer to my own question. The book’s code uses Math.max() as an outside check. Sorry for the silly question. This can be deleted.

0 Likes

#3

Hey Miles,

As you said, there is no difference between this two codes since both are doing same thing with slightly different ways.

0 Likes