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

问题描述

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

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 的一个 main(非递归)调用获得正确的结果。如果您为另一个(甚至相同的)列表再次调用它,它将不会从 0 重新开始,因此会给出错误的结果。

所以:

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

另请注意,变量 ptr 并没有真正发挥作用。不用它就行了:

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