Important Notice:

Practice-It will be discontinued as of November 1st, 2024. After this date, the website will remain online for a transitional period, but login will be restricted to University of Washington NetID authentication. This marks the next phase towards the platform's full retirement. Thank you for your use and support of the application over the years.

If you are looking for an alternative, a similar tool, CodeStepByStep, was developed independently by the original author of Practice-It, and is available at codestepbystep.com**

logo Practice-It logo

shift

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

Write a method shift that takes a stack of integers and an integer n as parameters and that shifts n values from the bottom of the stack to the top of the stack. For example, if a variable called s stores the following sequence of values:

    bottom [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] top

and we make the following call:

    shift(s, 6);
the method shifts the six values at the bottom of the stack to the top of the stack and leaves the other values in the same order producing:

    bottom [7, 8, 9, 10, 6, 5, 4, 3, 2, 1] top

Notice that the value that was at the bottom of the stack is now at the top, the value that was second from the bottom is now second from the top, the value that was third from the bottom is now third from the top, and so on, and that the four values not involved in the shift are now at the bottom of the stack in their original order.

If s had stored these values instead:

    bottom [7, 23, -7, 0, 22, -8, 4, 5] top

and we make the following call:

    shift(s, 3);

then s should store these values after the call:

    bottom [0, 22, -8, 4, 5, -7, 23, 7] 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 also may not solve the problem recursively. Your solution must run in O(n) time.

Your method should throw an IllegalArgumentException if the parameter n is less than 0 or greater than the number of elements in the stack. In writing your method, assume that you are using the Stack and Queue interfaces and the ArrayStack and LinkedQueue implementations discussed in lecture.

Write your solution to shift below.

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.