简体   繁体   English

递归C中的反向数组

[英]Reverse array in C recursively

Here's a part of my code, where I am trying to reverse a string recursively: 这是我的代码的一部分,在这里我试图递归地反转字符串:

    char reverse[10];
    gets(reverse);
    reverseString(reverse, (strlen(reverse) - 1));
    void reverseString(char ar[], int n)
    {
        if (n == 0)
        {
            return;
        }
        else
        {
            int temp = ar[n];
            ar[n] = *(ar);
            *(ar) = temp;
            reverseString((ar + 1), (n - 1));
        }
    }

When I enter the string "hello" it changes the string to "ohell". 当我输入字符串“ hello”时,它将字符串更改为“ ohell”。 I need it to reverse the string totally to "olleh". 我需要它来将字符串完全反转为“ olleh”。 Can someone help? 有人可以帮忙吗?

Since you swap the first and last element of the array, you should recursively call the function with the remaining n-2 elements (instead of n-1 ), 由于您交换了数组的第一个和最后一个元素,因此应使用其余的n-2元素(而不是n-1 )递归调用该函数,

void reverseString(char ar[], int n)
{
    if (n <= 0)
    {
        return;
    }
    else
    {
        int temp = ar[n];
        ar[n] = *(ar);
        *(ar) = temp;
        reverseString((ar + 1), (n - 2));
    }
}

(I have assumed that reverseString and reverseAr in your code are actually the same functions, perhaps some copy-paste error.) (我假设您的代码中的reverseStringreverseAr实际上是相同的函数,也许有些复制粘贴错误。)

# include <stdio.h>

/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if(*str)
   {
       reverse(str+1);
       printf("%c", *str);
   }
}

/* Driver program to test above function */
int main()
{
   char a[] = "Geeks for Geeks";
   reverse(a);
   getchar();
   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM