logo Practice-It logo

removeMax

Language/Type: Java Collections Stacks and Queues
Author: Stuart Reges (on 2014/02/13)

Write a method removeMax that takes a stack of integers as a parameter and that removes and returns the largest value from the stack. For example, if a variable called s stores the following:

    bottom [19, 8, 3, 19, 7, 3, 2, 42, 19, 3, 2, 7, 12, -8, 4] top

and we make the following call:

    int n = removeMax(s);

the method removes and returns the value 42 from the stack, so that the variable n will be 42 after the call and s will store the following values:

    bottom [19, 8, 3, 19, 7, 3, 2, 19, 3, 2, 7, 12, -8, 4] top

If the maximum value appears more than once, all occurrences of the maximum should be removed from the stack. For example, given the ending value of the stack above, if we again call removeMax(s), the method would return 19 and would leave the stack in the following state:

    bottom [8, 3, 7, 3, 2, 3, 2, 7, 12, -8, 4] top

You are to use one queue as auxiliary storage to solve this problem. You may not use any other auxiliary data structures to solve this problem, although you can have as many simple variables as you like. You may not use recursion to solve this problem and your solution must run in O(n) time where n is the size of the stack. Use the Stack and Queue interfaces and LinkedQueue and ArrayStack implementations described in the cheat sheet. Your method should throw an IllegalArgumentException if the stack is empty.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.