0

I have a trouble of understanding the calling stack of reverse a string use follow code:

public static String reverseString(String str) {
        String reverse = "";
        if (str.length() == 1) {

            return str; 
        } else {
            reverse += str.charAt(str.length() - 1) + reverseString(str.substring(0, str.length() - 1));
            return reverse;
        }
    }

You can see the stack build up from 1 to 4 and then pop from 4 to 1. Take str = "abcd" as an example. It should returns "a" first (since "a" pop from calling stack firstly) which does not reverse a string. Am I getting something wrong here? thanks!

enter image description here

3
  • 1
    Yuck. new StringBuilder(str).reverse().toString() Commented Nov 19, 2018 at 4:48
  • @Elliott Frisch Thanks. Just try to figure out recursion part. Commented Nov 19, 2018 at 4:52
  • You get this return value in the else branch of the incarnation that was called with string "ab". This returns the last character 'b' concatenated with the return value "a". Commented Nov 19, 2018 at 4:55

2 Answers 2

1

Your program work fine But you unable trace your program. Below i show stack frame of all recursive call in your program(both stack up and stack down). stacktraceimage

Sign up to request clarification or add additional context in comments.

Comments

1

Consider carefully the following block in the code:

else {
        reverse += str.charAt(str.length() - 1) + reverseString(str.substring(0, str.length() - 1));
        return reverse;
    }

The calling stack, is recursing the function with the last character excluded, and the excluded character is appended to the variable reverse. What you're missing in your understanding is, first the call stack is returning the last excluded character, which is 'd', not 'a' as you mentioned, and appending it to string 'reverse'.

Reiterating the code manually:
reverse       input //reverseString(input)
1. d        abcd
2. c       abc
3. b       ab
4. a       a //return a as length is 1, the if block

You can see the reverse string building up with each call.

2 Comments

Thanks. I remember the calling stack should build itself bottom-up. The first call is "1. d abcd" therefore it is should be last one in the stack?
Yes, d will be the last one in the stack. However, Stack is LIFO structure(Last In First Out). Hence, d will come out first, then c and so on..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.