Recursive Algorithm 6-Reversed Strings in Complex Recursion

Complex recursive algorithms require some processing during the process of recursively calling functions, such as saving or modifying element values. Reversing strings, Japanese decomposition, and the Tower of Hanoi problem are all complicated recursive algorithms.

Reverse a string
Use recursion to reverse a string and store it back in the original string.

【analysis】

Assuming that the string is stored in the array s, the prototype of the recursive function is as follows:

int RevStr(char s[], int i);

In order to reverse the character at the current position, you need to find the storage position in the current string after the reversal. The function first reads the character at the current position into a variable ch. If the character at the current position is the end character, the function returns 0 to inform the last recursive call to the function that the last character should be stored in the first position of the string. Code:

char ch=s[i];
if(ch=='\0')
    return 0;


For other cases, the function recursively calls RevStr with the string s and the character position i+1 as parameters, finds the storage position k of the current character, and stores the character in position k. At the same time, the next position is used to store the previous one character. Code:

k=RevStr(s,i+1);
s[k]=ch;
return k+1;

Code:

#include<stdio.h>
int RevStr(char s[], int i);
void main()
{
	char s[] = "Welcome to Northeast University!";
	printf("颠倒前:%s\n", s);
	RevStr(s, 0);
	printf("颠倒后:%s\n", s);
	getchar();
}
int RevStr(char s[], int i)
{
	int k;
	char ch = s[i];
	if (ch == '\0')
		return 0;
	else
	{
		k = RevStr(s, i + 1);
		s[k] = ch;
		return k + 1;
	}
}

result:


 

Guess you like

Origin blog.csdn.net/baidu_36669549/article/details/104141681