logo Practice-It logo

isSorted

Language/Type: Java Collections Stacks and Queues
Author: Roy McElmurry

Write a method called isSorted that takes a stack of integers and returns true if the stack is sorted and false otherwise. A stack is considered sorted when its integers are in non-decreasing order (i.e. increasing order with duplicates allowed) when read from bottom to top.

So, a sorted stack has its smallest integer on the bottom and its largest integer on the top. A stack that contains fewer than two integers is sorted by definition. For example, suppose that a variable called s stores the following sequence of values:

bottom [-12, 0, 1, 8, 8, 8] top 

then a call on isSorted(s) should return true. If s had instead contained the following values:

bottom [-9, 10, 43, 24, 97] top 

then a call on isSorted(s) should return false, because 24 is less than 43. You may 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. At the end of the call to your method, the stack's contents must be the same as they were before the method was called; do not destroy the stack.

You have access to the following two methods and may call them as needed to help you solve the problem:

 
public static void s2q(Stack s, Queue q) { ... }
public static void q2s(Queue q, Stack s) { ... }
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.