c-从函数返回链表的头



我创建的函数获取两个结构链表的头,并使用它们更新第一个链表中结构的一个成员。一旦我的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 pointer来保持其原始链表头(如head_p = ...inputed head node...),然后使用visitor pointer来访问链表(如visitor_p = visitor_p->next)。在您的代码中,tmp就是head pointer

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 
}

相关内容

  • 没有找到相关文章

最新更新