4.13.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <stdio.h>
  2. void rvrs(char[]);
  3. int rev (char [], int , int );
  4. void swap(char s[], int in, int out);
  5. int main()
  6. {
  7. char x[]="1 2 3 4 5 6 7 8 9 10 11 12";
  8. rvrs(x);
  9. printf ("%s\n",x);
  10. return 0;
  11. }
  12. /** recursively reverse string, lisp style */
  13. // (defun rev (s)
  14. void rvrs(char in[])
  15. {
  16. if (in!=0)
  17. rev(in,0,0);
  18. }
  19. int rev (char in[], int inpos, int outpos) //returns outpos
  20. {
  21. // (if (> (length s) 1)
  22. // if (in!=0) we check this above
  23. if (in[inpos]!='\0')
  24. {
  25. if(in[inpos+1]!='\0')
  26. // (append (rev (cdr s)) (list (car s)))
  27. {
  28. int outposnew=rev(in,inpos+1,outpos); // O(1)*O(N) ~ O(N) space reverse O(N) time.
  29. if (inpos > outposnew)
  30. {
  31. swap(in,inpos,outposnew);
  32. return outposnew+1;
  33. }
  34. return outposnew;
  35. }
  36. else { // last element
  37. // s)
  38. if (inpos > outpos)
  39. {
  40. swap(in,inpos,outpos);
  41. return outpos+1;
  42. }
  43. return outpos;
  44. }
  45. }
  46. }
  47. void swap(char s[], int in, int out)
  48. {
  49. // swap
  50. char temp;
  51. temp=s[in];
  52. s[in]=s[out];
  53. s[out]=temp;
  54. }