With recursion, it always helps to think of it as 2 parts, the “Setup” and the recursive function. Your setup will create the correct situation (create two stacks, pass them, etc.), and then call the recursive method, and when the recursive method is executed, report the results.
In your case, you probably want this signature for the "recursive" method:
public boolean compareStacks(Stack one, Stack two)
If this method pops up and compares the top elements of the stack tow, it can return false right then (saying that they are not compared). If they do, you now have two stacks, each one shorter than before. You already know how to compare these two stacks, correctly (you just wrote a method for this!).
at the end, you can “Push” your one element back onto each stack to restore its previous state before returning.
There will be little difficulty in restoring the stack when they are not being compared, and ensuring that if compareStack fails you call, it passes it correctly to the previous state, even if the "current" compareStack is successfully completed, but these are implementation details - I just thought that I mention them so you don’t miss them.
There is a good solution with Try / finally (without catching, returning from try and returning back to the stack at the end), which will make the code pretty smooth, but it is quite simple without it.
Bill k
source share