zoukankan      html  css  js  c++  java
  • 算法提高: 递归倒置字符数组(递归)

    问题描述
      完成一个递归程序,倒置字符数组。并打印实现过程
      递归逻辑为:
      当字符长度等于1时,直接返回
      否则,调换首尾两个字符,在递归地倒置字符数组的剩下部分
    输入格式
      字符数组长度及该数组
    输出格式
      在求解过程中,打印字符数组的变化情况。
      最后空一行,在程序结尾处打印倒置后该数组的各个元素。
    样例输入
    Sample 1
    5 abcde
    Sample 2
    1 a

     样例输出

     

    Sample 1
    ebcda
    edcba
    edcba
    Sample 2
    a
    

     注意:puts函数会自动换行

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 
     4 void swap(int a, int b, char* s)
     5 {
     6     char temp = s[a];
     7     s[a] = s[b];
     8     s[b] = temp;
     9 }
    10 
    11 void fun(int start, int mid, int end, char *s)
    12 {
    13     if (start == mid)
    14     {
    15         return 0;
    16     }
    17     else
    18     {
    19         swap(start, end - start - 1, s);
    20         puts(s);
    21         fun(start + 1, mid, end, s);
    22     }
    23 }
    24 
    25 int main(void)
    26 {
    27     int len;
    28     char *s;
    29     int i;
    30 
    31     scanf("%d", &len);
    32     getchar();
    33     s = (char *)malloc(sizeof(char)*len);
    34     memset(s, 0, len);
    35     gets(s);
    36 
    37     fun(0,len/2,len, s);
    38     printf("%s", s);
    39 
    40     return 0;
    41 }
  • 相关阅读:
    [RxJS] throwIfEmpty
    [Kotlin] I/O readline
    [Kotlin] Generic Functions
    [Kotlin] Generics basic
    [CSS 3] Use Multiple Background Images to Create Single Element CSS Art
    [Kotlin] Visibilities
    [Kotlin] Getter and Setter
    [Kotlin] Enum class
    [Kotlin] Singleton Object
    面试问Redis集群,被虐的不行了......
  • 原文地址:https://www.cnblogs.com/ZhengLijie/p/12552769.html
Copyright © 2011-2022 走看看