我创建的函数采用两个结构链表的头,并使用它们来更新第一个链表中的结构成员。一旦我的 while 循环完成,我希望返回结构体“a”的头部,但是当前当我返回它时,由于 while 循环,它的值为 NULL。更新后,我如何返回“a”的头部?我知道我必须使用临时结构,但我将如何实现它?
struct artist *update_counts(struct artist *a, struct play *p)
{
struct artist *tmp = a;
int count = 0;
while (a != NULL)
{
while (a->artist_id == p->artist_id)
{
count += p->playcount;
p = p->next;
}
a->playcount = count;
a = a->next;
count = 0;
}
return a;
}
最佳答案
通常,要访问链表,我们可以使用头指针
来保留其原始链表头,例如head_p = ...输入的头节点...
,然后使用访问者指针
来访问链表,如visitor_p = Visitor_p->next
。在您的代码中,tmp
是头指针
。
struct artist *update_counts(struct artist *a, struct play *p)
{
struct artist *tmp_head = a;//tmp is the head of inputed linked list a
int count = 0;
while (a != NULL)
{
while (a->artist_id == p->artist_id)
{
count += p->playcount;
p = p->next;
}
a->playcount = count;
a = a->next;
count = 0;
}
return tmp_head;//just return the head of a
}
关于c - 从函数返回链表的头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007247/