C语言三种方法逆序输出字符串

两种递归:

#include 
#include 

void reverse(char* str) {
	char tmp = *str;
	int len = strlen(str);
	*str = *((len - 1) + str);
	*((len - 1) + str) = '\0';
	if (strlen(str + 1) >= 2) {
		reverse(str + 1);
	}
	*((len - 1) + str) = tmp;
}

int main() {
	char arr[] = "abcdef";
	reverse(arr);
	printf("%s", arr);
	return 0;
}
#include 
#include 

void reverse(char arr[], int left, int right) {
	char tmp = arr[left];
	arr[left] = arr[right];
	arr[right] = tmp;
	if(left

一种非递归:

#include 
#include 

void reverse(char arr[],int left,int right) {
	while (left < right) {
		char tmp = arr[left];
		arr[left] = arr[right];
		arr[right] = tmp;
		left++;
		right--;
	}
}
int main() {
	char arr[] = "abcdef";
	int left = 0;
	int right = strlen(arr)-1;
	reverse(arr, left, right);
	printf("%s", arr);
	return 0;
}

你可能感兴趣的:(C语言,c语言,算法,数据结构)