c - 从函数返回链表的头

标签 c struct linked-list return

我创建的函数采用两个结构链表的头,并使用它们来更新第一个链表中的结构成员。一旦我的 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/

相关文章:

c - 你如何构造一个 C makefile 以便它编译 source.c 文件?

c - 这些代码行怎么会导致完全相同的程序有时崩溃但其他程序运行良好?

c - 在 main 中使用头文件中的结构(在 C 中)

c - 为什么我的双链表插入失败?

c - 读取文件时内存分配问题

检查一个字符串在 C 中是否只有空白字符

c++ - sizeof 不会显示实际大小,尝试实现 ip

java.lang.ClassCastException : Creating a synchronized Linked List 异常

c - 在 C 中使用字符串对链表进行排序

比较 C 中的两个数组值