C语言 我写了一个简单的函数来递归地反转链表.它返回更新的头部指针


struct node* reverse(struct node *head)  
{  
static struct node *prev =NULL;  
if(head==NULL) return prev;  
struct node *q = head->next;  
head->next=prev;  
prev=head;  
return reverse(q);  
}    

我认为它没有任何问题。谁能建议我是否做错了什么

如果您尝试使用此函数两次,那么您将体验的行为将与您想要的行为不同,因为 static 变量只使用一次。取而代之的是,我建议这样的事情:

struct node* reverse(struct node *current, isHead)
{
    if (current->next == NULL)
    {
        return current;
    }
    struct node* ret = reverse(current->next);
    if (isHead)
    {
        current->next = NULL;
    }
    current->next->next = current;
    return ret;
}

这里有几个问题。 您绝对不想将static变量用于这样的事情。 请尝试以下操作:

struct node *reverse(struct node *head)
{
    if (head == NULL) return NULL;
    struct node *q = head->next;
    if (q == NULL) return head;
    struct node *r = reverse(q);
    q->next = head;
    head->next = NULL;
    return r;
}

该函数的问题在于您不能多次调用它:)因为静态局部变量prev仅在(之前)第一次调用函数时初始化一次。

最新更新