123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- #include <stdio.h>
- void rvrs(char[]);
- int rev (char [], int , int );
- void swap(char s[], int in, int out);
- int main()
- {
- char x[]="1 2 3 4 5 6 7 8 9 10 11 12";
- rvrs(x);
- printf ("%s\n",x);
- return 0;
- }
- /** recursively reverse string, lisp style */
- // (defun rev (s)
- void rvrs(char in[])
- {
- if (in!=0)
- rev(in,0,0);
- }
- int rev (char in[], int inpos, int outpos) //returns outpos
- {
- // (if (> (length s) 1)
- // if (in!=0) we check this above
- if (in[inpos]!='\0')
- {
- if(in[inpos+1]!='\0')
- // (append (rev (cdr s)) (list (car s)))
- {
- int outposnew=rev(in,inpos+1,outpos); // O(1)*O(N) ~ O(N) space reverse O(N) time.
- if (inpos > outposnew)
- {
- swap(in,inpos,outposnew);
- return outposnew+1;
- }
- return outposnew;
- }
- else { // last element
- // s)
- if (inpos > outpos)
- {
- swap(in,inpos,outpos);
- return outpos+1;
- }
- return outpos;
- }
- }
- }
- void swap(char s[], int in, int out)
- {
- // swap
- char temp;
- temp=s[in];
- s[in]=s[out];
- s[out]=temp;
- }
|