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

C 我编写了一个简单的函数来递归地反转链表。它返回更新的头指针,c,algorithm,linked-list,C,Algorithm,Linked List,我看不出有什么问题。有人能告诉我我是否做错了什么吗?函数的问题是,您不能多次调用它。:)因为静态局部变量prev在第一次调用函数时只初始化了一次。这里有一些问题。您肯定不想使用静态变量来实现类似的功能。请尝试以下操作: struct node* reverse(struct node *head) { static struct node *prev =NULL; if(head==NULL) return prev; struct node *q = head->next

我看不出有什么问题。有人能告诉我我是否做错了什么吗?

函数的问题是,您不能多次调用它。:)因为静态局部变量
prev
在第一次调用函数时只初始化了一次。

这里有一些问题。您肯定不想使用
静态
变量来实现类似的功能。请尝试以下操作:

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 *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;
}

你测试的时候发生了什么?。。列表中只有两个条目,使事情变得更简单、更清楚。。。。当您逐步使用调试器时,在每一步记录所有var值。假设您有两个列表,并且想要反转这两个列表,或者想要反转一个列表两次。那个
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;
}