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);
}
我没有看到任何问题。任何人都可以建议我做错了什么
答案 0 :(得分:2)
如果您尝试使用此功能两次,那么您将遇到的行为将与您想要的行为不同,因为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;
}
答案 1 :(得分:1)
这里有一些问题。你绝对不希望在这样的事情上使用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;
}
答案 2 :(得分:0)
该函数的问题在于,您可能不会多次调用它。:)因为静态局部变量prev
仅在第一次调用函数时(之前)初始化一次。 / p>