赞
踩
两种递归:
- #include <stdio.h>
- #include <string.h>
-
- 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 <stdio.h>
- #include <string.h>
-
- void reverse(char arr[], int left, int right) {
- char tmp = arr[left];
- arr[left] = arr[right];
- arr[right] = tmp;
- if(left<right)
- reverse(arr, left + 1, right - 1);
- }
-
- int main() {
- char arr[] = "abcdef";
- int left = 0;
- int right = strlen(arr)-1;
- reverse(arr, left, right);
- printf("%s", arr);
- return 0;
- }
一种非递归:
- #include <stdio.h>
- #include <string.h>
-
- 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;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。