How to reverse a string using a recursive function, without
swapping or using an extra memory?
Answer Posted / stephen
#include <iostream>
#include <string>
using namespace std;
char * reverse (char *); //function prototype
int length(char *); //function prptotype
int main()
{
int i;
char *str = new char[6], *rev = new char[6];
cin >> str;
strcpy(rev,reverse(str));
cout <<"Original "<< str << " reverse " << rev << endl;
free(str);
free(rev);
return 0;
}
int length(char *s)
{
int i;
for (i=0; *(s+i)!='\0' ; ++i);
return i;
}
char *reverse(char *s)
{
char *t;
int i, n;
n=length(s);
t = new char[n];
for (i=0; i<n; ++i)
{
*(t+i)=*(s+n-1-i);
}
*(t+i)='\0';
return t;
}
/*based off of answer 8 i took this an intialized the
pointers so that it would run, and switched it over to the
C++ standard output commands. His algorithm was correct, he
just forgot to setup the memory*/
| Is This Answer Correct ? | 10 Yes | 14 No |
Post New Answer View All Answers
What is clrscr in c?
Why isnt any of this standardized in c?
What are near, far and huge pointers?
Is c is a middle level language?
Explain what is a 'locale'?
What would happen to X in this expression: X += 15; (assuming the value of X is 5)
What is hashing in c?
How main function is called in c?
When we use void main and int main?
Linked lists -- can you tell me how to check whether a linked list is circular?
Is the exit() function same as the return statement? Explain.
Can I use base-2 constants (something like 0b101010)? Is there a printf format for binary?
Why doesnt this code work?
What is the purpose of ftell?
Can we declare a function inside a function in c?