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]; //opps have to add 1 here or there
wont be room for a null!
for (i=0; i<n; ++i)
{
*(t+i)=*(s+n-1-i);
}
*(t+i)='\0';
return t;
}
//can only handle words 5 letters or less.
/*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
| Is This Answer Correct ? | 8 Yes | 13 No |
Post New Answer View All Answers
Process by which one bit pattern in to another by bit wise operation is?
a character or group of characters that defines a register,or a part of storage a) memory b) byte c) address d) linear list
How do I swap bytes?
What are Macros? What are its advantages and disadvantages?
What is the role of this pointer?
What does the error 'Null Pointer Assignment' mean and what causes this error?
What is the use of function in c?
How can I find out the size of a file, prior to reading it in?
a linearly ordered set of data elements that have the same structure and whose order is preserved in storage by using sequential allocation a) circular b) ordinary c) array d) linear list
Explain two-dimensional array.
explain what are actual arguments?
Is register a keyword in c?
What are variables and it what way is it different from constants?
What is pivot in c?
What is null pointer in c?