我已经检查了我的显示功能,它运行良好。但我的以下功能无法正常工作。最初列表有“66 55 44 33 22 11”
void deleteFOdd(struct Node*head)
{
struct Node* last=head,*t=head;
while(last->next!=head)
{
last=last->next;
}
last->next=t->next;
head=t->next;
free(t);
}
我不明白为什么它在删除第一个节点后无限次打印数组。
正如 H.cohen 指出的那样在注释中,在函数中局部更改 head
参数对函数外的值没有影响。您需要以某种方式将更新后的头部返回给调用者。根据 Jonathan Leffler 的建议,这可以通过返回更新后的头指针(调用者需要将其存储在某个地方,可能在传递给函数的同一个变量中)来完成,或者可以将函数参数更改为指向指向头。
方法一——返回新头
struct Node* deleteFOdd(struct Node*head)
{
struct Node* last=head,*t=head;
while(last->next!=head)
{
last=last->next;
}
last->next=t->next;
head=t->next;
free(t);
return head;
}
上面的代码有一个错误,因为它没有处理包含单个元素的列表的情况。我建议在这种情况下返回 NULL
。此外,如果函数在开始时检查 head
是否为 NULL
,那就太好了。这是修改后的版本:
struct Node* deleteFOdd(struct Node*head)
{
struct Node* last=head,*t=head;
// optional: deal with NULL list
if (head==NULL)
{
return head;
}
while(last->next!=head)
{
last=last->next;
}
if (last==head)
{
// list contained only 1 element
head=NULL;
}
else
{
last->next=t->next;
head=t->next;
}
free(t);
return head;
}
调用者可以调用函数如下:
head = deleteFOdd(head);
方法2——传递一个指向头指针的指针
下面是在上面修改的版本的基础上,但是使用了一个指向指针的指针来传回更新后的头指针。
void deleteFOdd(struct Node** headp)
{
struct Node* head=*headp;
struct Node* last=head,*t=head;
// optional: deal with NULL list
if (head==NULL)
{
return;
}
while(last->next!=head)
{
last=last->next;
}
if (last==head)
{
// list contained only 1 element
head=NULL;
}
else
{
last->next=t->next;
head=t->next;
}
free(t);
*headp = head;
}
调用者可以调用函数如下:
deleteFOdd(&head);