In java and using recursion Write a method stutter that accepts a Stack of integ
ID: 3576161 • Letter: I
Question
In java and using recursion
Write a method stutter that accepts a Stack of integers as a parameter and replaces every value in the stack with two occurrences of that value. For example, suppose a stack stores these values:
Then the stack should store the following values after the method terminates:
Notice that you must preserve the original order. In the original stack the 9 was at the top and would have been popped first. In the new stack the two 9s would be the first values popped from the stack. Also, you must not use any auxillary data structures to solve this problem. If the original stack is empty, the result should be empty as well.
Explanation / Answer
public Stack stutter(Stack intStack) //STARTS: Bot[3,7,1,14,9] TOP { Queue temp; while(!intStack.empty()) { temp.offer(temp.pop()); // Back [3,7,1,14,9] Front } while(!temp.empty()) { intStack.push(temp.remove()); //BOT[9,14,1,7,3] TOP } while(!intStack.empty()) { temp.offer(temp.pop()); //BACK[9,14,1,7,3] Front } while(!temp.empty()) { intStack.push(temp.peek()); intStack.push(temp.remove()); //BOT[3,3,7,7,1,1,14,14,9,9] TOP } return intStack; }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.