首页 文章

从函数返回链表的头部

提问于
浏览
0

我创建的函数接受两个链接结构列表的头部,并使用它们来更新第一个链表中结构的成员 . 一旦我的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;
}

1 回答

  • 0

    通常,要访问链表,我们可以使用 head pointer 保持其原始链表头像 head_p = ...inputed head node... ,然后使用 visitor pointer 访问链接列表,如 visitor_p = visitor_p->next . 在您的代码中, tmphead 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 
    }
    

相关问题