|
11 | 11 | #define MAXLEN 1000
|
12 | 12 |
|
13 | 13 | /* functions */
|
14 | | -void reverse(char []); |
| 14 | +void reverse(char s[]); |
| 15 | +void reverse_inplace(char str[], int begin, int end); |
| 16 | +void swap(char arr[], size_t i, size_t j); |
15 | 17 |
|
16 | | -/* reverse function: reverse string s in place, recursive version */ |
| 18 | +/* reverse: interface function to reverse_inplace */ |
17 | 19 | void reverse(char s[])
|
18 | 20 | {
|
19 | | - int c; |
20 | | - static unsigned long i = 0, j = 0; |
| 21 | + reverse_inplace(s, 0, strlen(s) - 1); |
| 22 | +} |
| 23 | + |
| 24 | +/* reverse_inplace: reverse string s in place, recursive version */ |
| 25 | +void reverse_inplace(char str[], int begin, int end) |
| 26 | +{ |
| 27 | + if (begin > end) /* exit condition */ |
| 28 | + return; |
| 29 | + swap(str, begin, end); |
| 30 | + reverse_inplace(str, ++begin, --end); |
| 31 | +} |
| 32 | + |
| 33 | +/* swap: interchange v[i] and v[j] */ |
| 34 | +void swap(char v[], size_t i, size_t j) |
| 35 | +{ |
| 36 | + char tmp; |
21 | 37 |
|
22 | | - if (j < strlen(s) - 1) { |
23 | | - ++j; |
24 | | - reverse(s); |
25 | | - } |
26 | | - if (i < j) { |
27 | | - c = s[i]; |
28 | | - s[i++] = s[j]; |
29 | | - s[j--] = c; |
30 | | - } |
| 38 | + tmp = v[i]; |
| 39 | + v[i] = v[j]; |
| 40 | + v[j] = tmp; |
31 | 41 | }
|
32 | 42 |
|
33 | 43 | int main(void)
|
34 | 44 | {
|
35 | 45 | char str[MAXLEN];
|
36 | 46 |
|
37 | | - printf("Enter a string to reverse:\n"); |
| 47 | + printf("Enter a string to reverse:"); |
38 | 48 | scanf("%s", str);
|
39 | 49 | reverse(str);
|
40 | 50 | printf("%s\n", str);
|
|
0 commit comments