Need help with my recursive program that reverses the input [duplicate]
Possible Duplicate:
Write a recursive function that reverses the input
Recently, I've been reading the book C++ For Everyone and I've been having trouble putting together a recursive function (Confusing to think about...)
The question was: Write a recursive function string reverse(string str)
that returns the reverse of str
This is what I have so far:
string reverse(string str)
{
string word = "";
if (str.length() <= 1)
{
return str;
}
else
{
string str_copy = str;
int n = str_copy.length() - 1;
string last_letter = str_copy.substr(n, 1);
str_copy = str_copy.substr(0, n);
word += reverse(str_copy);
开发者_StackOverflow中文版 return last_letter;
}
return word;
}
My problems now is:
If I enter wolf
, it returns f
If I change return last_letter
to return word
, I get w
If I change to return str_copy
, I get wol
You need to return the combination of the the last character (last_letter
) and the reversal of the rest of the string, but you don't do that in any of your attempts. You only ever return one part or the other.
string reverse(string str)
{
int len = str.length();
if (len <= 1)
{
return str;
}
else
{
return str.substr(len-1, 1) + reverse( str.substr(0, len-1) );
}
}
This would do the work:
Delete return last_letter;
Change `
word += reverse(str_copy);
to
word = last_letter+reverse(str_copy);
I'll leave the thinking to you!
Best.
精彩评论