简体   繁体   English

创建非尾递归 function 的问题(c++ 新手)

[英]Problems with creating Non-tail Recursive function (New to c++)

I've been working on solving this Reverse String and Non-Tail Recursion C++ problem.我一直在努力解决这个反向字符串和非尾递归 C++ 问题。 I've been able to write it successfully using libraries (STL, strlen) but need to be able to right it with just one int and one char in the function and no libraries.我已经能够使用库(STL、strlen)成功编写它,但需要能够在 function 中仅使用一个 int 和一个 char 来纠正它,并且没有库。

This is what I'm aiming the code to look like but with the ReverseString function matching the specific restrictions.这就是我的目标代码看起来像,但 ReverseString function 匹配特定限制。

#include <iostream>

using namespace std;

// constant
const int STRING_AMOUNT = 100;

// protocol
int ReverseString(char*);

// main method
int main() {
  char theString[STRING_AMOUNT] = "abcde";
  cout << "The string is: " << endl;
  cout << theString << endl << endl;
  cout << "Reversing the Function" << endl;
  ReverseString(theString);
  cout << "The string contains: " << endl;
  cout << theString << endl;
  // exit program
  return 0;
}

int ReverseString(char* reverseString) {

}

I'm thinking that we could use the int return value to find the length of the string.我在想我们可以使用 int 返回值来查找字符串的长度。

For our base case, a string that is just the null terminator '\0' will always be zero.对于我们的基本情况,只是 null 终止符'\0'的字符串将始终为零。

if (*c == '\0') {
    return 0;
}

Starting from "abcde" , which has a null terminator appended at the end, we can't know for sure when the string will end."abcde"开始,它的末尾附加了一个 null 终止符,我们无法确定字符串何时结束。 So we figure that the length of the string will always be 1 greater than the pointer, advanced one step ahead, which will make the char * point to "bcde" , as so on.所以我们计算出字符串的长度总是比指针大 1,提前一步,这将使 char * 指向"bcde" ,依此类推。

return 1 + StringReverse(c + 1);

And that's pretty much it for the recursive function.这就是递归 function 的内容。

int StringReverse(char *c) {
    if (*c == '\0') {
        return 0;
    }
    return 1 + StringReverse(c + 1);
}

Now this won't do anything on its own, the inner calls of the function won't know where the beginning of the string is to allow for swapping... except for the place that initially called it.现在这不会自己做任何事情,function 的内部调用将不知道字符串的开头在哪里允许交换......除了最初调用它的地方。

So we wrap the recursive function call with another function that performs the swapping.所以我们用另一个执行交换的 function 包装递归 function 调用。

void ReverseString(char *start) {
    int size = StringReverse(start);

    // The swap code goes here...
}

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

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