File tree Expand file tree Collapse file tree 1 file changed +24
-14
lines changed Expand file tree Collapse file tree 1 file changed +24
-14
lines changed Original file line number Diff line number Diff line change 1111#define MAXLEN 1000
1212
1313/* 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 );
1517
16- /* reverse function: reverse string s in place, recursive version */
18+ /* reverse: interface function to reverse_inplace */
1719void reverse (char s [])
1820{
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 ;
2137
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 ;
3141}
3242
3343int main (void )
3444{
3545 char str [MAXLEN ];
3646
37- printf ("Enter a string to reverse:\n " );
47+ printf ("Enter a string to reverse: " );
3848 scanf ("%s" , str );
3949 reverse (str );
4050 printf ("%s\n" , str );
You can’t perform that action at this time.
0 commit comments