Homework: Sequence Implementation on Stack


This homework is necessary preparation for the lab. Make sure you type your answers in files you bring to the lab so that you will not have to waste time entering your code during the lab.

  1. Implement the following method that, given two stacks and an integer, moves entries between the two stacks so that the length of the first stack is equal to the given integer. Note that, as the ensures clause states, rev(leftStack) * rightStack must not be changed by the method.
        /**
         * Shifts entries between {@code leftStack} and {@code rightStack}, keeping
         * reverse of the former concatenated with the latter fixed, and resulting
         * in length of the former equal to {@code newLeftLength}.
         * 
         * @param <T>
         *            type of {@code Stack} entries
         * @param leftStack
         *            the left {@code Stack}
         * @param rightStack
         *            the right {@code Stack}
         * @param newLeftLength
         *            desired new length of {@code leftStack}
         * @updates leftStack, rightStack
         * @requires <pre>
         * 0 <= newLeftLength  and
         * newLeftLength <= |leftStack| + |rightStack|
         * </pre>
         * @ensures <pre>
         * rev(leftStack) * rightStack = rev(#leftStack) * #rightStack  and
         * |leftStack| = newLeftLength}
         * </pre>
         */
        private static <T> void setLengthOfLeftStack(Stack<T> leftStack,
                Stack<T> rightStack, int newLeftLength) {...}
    

    Note that setLengthOfLeftStack is a static, generic method: it is parameterized by the type T of the entries in the stacks. You can use the type T wherever you need to declare a variable that refers to an object of type T.

  2. Develop a complete test plan for the Sequence constructor and kernel methods (add, remove, and length) and enter them in SequenceTest.

For the homework, turn in printouts of your implementation of setLengthOfLeftStack and of the SequenceTest.java file.