看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《gs9706 (神手)》之銘言: : 題目是這樣的.... : Write a recursive function to reverse a string by C. : For example, char a[ ] = "ABCDEFGH" ; : printf (" %s \n", a); /* "ABCDEFGH" */ : reverse_string (a); : printf (" %s \n", a); /* "HGFEDCBA" */ : 我怎麼想都想不出只傳一個位址參數的方法 : 又要遞迴..... : 懇請解救~~~ int reverse_string(char *); char str[] = "123456789"; call time | reserve c call next str value | main:123456789 | a:123456789 | 1 b:123456789 | 2 c:123456789 | 3 d:123456789 | 4 e:123456789 | 5 f:123456789 | 6 g:123456789 | 7 h:123456789 | 8 return time| back time after copy after put c return back str value | c str value i:123456789 | h:123456798 | 8 123456789 123456799 123456798 g:123456987 | 7 123456798 123456988 123456987 f:123459876 | 6 123456987 123459877 123459876 e:123498765 | 5 123459876 123498766 123498765 d:123987654 | 4 123498765 123987655 123987654 c:129876543 | 3 123987654 129876544 129876543 b:198765432 | 2 129876543 198765433 198765432 a:987654321 | 1 198765432 987654322 987654321 main:987654321 | 987654321 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.74.9.2
csihcs:if(!str || str[0] == '\0') return 0; 07/04 23:24
csihcs:else if(str[1] == '\0') return 1; 07/04 23:25
csihcs:... ; i = reverse_string(str); ... ; return i+1; 07/04 23:26
ledia:len = strlen(str); if(len <= 1) return; 07/06 01:47
ledia:swap(str[0], str[len-1]); 07/06 01:47
ledia:backup str[len-1]; str[len-1] = '\0'; 07/06 01:48
ledia:reverse_string(str+1); 07/06 01:48
ledia:restore str[len-1]; 07/06 01:48
ledia:好醜 ._. 07/06 01:49