c - return 并没有破坏我在 c 中的递归函数

标签 c recursion

struct Node *xFromEnd(struct Node *pHead, int x)
{
    static int temp = 1;

    if (pHead->next != NULL)
        xFromEnd(pHead->next, x);
    if ((temp++) == x)
        return pHead;
}

满足条件时如何跳出该函数?返回只是在调用堆栈上进一步向上(转到其上一个函数调用),而不是退出并转到 main。我怎样才能做到这一点?

最佳答案

struct Node *xFromEnd(struct Node *pHead, int x){
    static int temp = 1;//but can not reset !!

    if(pHead == NULL)
        return NULL;
    struct Node *p = xFromEnd(pHead->next, x);
    if (p == NULL){
        return (x == temp++) ? pHead : NULL;
    }
    return p;
}

关于c - return 并没有破坏我在 c 中的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29021299/

相关文章:

c - 从 C 代码中删除文件

c - 使用 BackupRead 功能时出现问题

c - 空或终止金丝雀

具有强力回溯错误的 Python 数独递归

algorithm - 给定 n 个苹果出售的最大利润

Church 平等编码的递归

regexec 可以用于使用二进制文件查找匹配项吗?

c - 我的strtok()实现(C)有什么问题?

python - python中的递归函数

Haskell 列表递归 - 为什么一个有效而另一个无效?