Recursion 为什么以下查找链表长度的函数返回的值不正确?

Recursion 为什么以下查找链表长度的函数返回的值不正确?,recursion,data-structures,linked-list,static,singly-linked-list,Recursion,Data Structures,Linked List,Static,Singly Linked List,请找出逻辑上的错误。 为什么以下查找链表长度的函数返回的值不正确 int getCount(struct Node* head){ static int count =0; Node* ptr = head; if(ptr==NULL) return count; else { count++; getCount(ptr->next); } } 由于函数的签名

请找出逻辑上的错误。 为什么以下查找链表长度的函数返回的值不正确

int getCount(struct Node* head){
      
    static int count =0;
    Node* ptr = head;
    
    if(ptr==NULL)
        return count;
    else
    {
        count++;
        getCount(ptr->next);
    }
    
}

由于函数的签名表明它应该返回节点数,
else
块有问题:它从不返回任何内容

此外,您实际上不需要
count
。更好的做法是使用返回值并将其加上1。
static count
的问题是,对于
getCount
的一个主(非递归)调用,您只能得到正确的结果。如果您为另一个(甚至相同的)列表再次调用它,它将不会在0处重新启动,因此将给出错误的结果

因此:

还要注意的是,变量
ptr
实际上并不起作用。不用它就行了:

int getCount(struct Node* head){
    if(head==NULL)
        return 0;
    else
        return 1 + getCount(head->next);
}

谢谢你的回复。我已经更新了有问题的代码。您现在可以检查一下为什么返回不正确的值吗?(计数是静态的)请不要更改问题中的代码。这使我的答案看起来无关紧要。好的,恢复了更改。但是你能帮我吗。如果我将“getCount(ptr->next)”替换为“returngetcount(ptr->next)”。这应该可以工作,因为计数是静态的。但它不起作用。无法理解。请参阅第二段对我答案的补充。使用
static count
return getCount
时,它仅在第一次正常工作。这是否回答了您的问题?您得到的值不正确?所需的输出和您的输出是什么?
int getCount(struct Node* head){
    if(head==NULL)
        return 0;
    else
        return 1 + getCount(head->next);
}