C语言 链表 怎么统计每个班级的人数?

图片说明
输入完数据后,怎么统计每个班级的学生数量?

第一个回答的方法比较普遍,用来统计学生数量。
现在可以看看第二个回答中的方法,

 strcut your_struct_name {
    //your element
    static int count;
    Construct(){
        //your construct
        ++count;
    }
    Destructor(){
        //your destruct
        --count;
    }
};

int your_struct_name::count = 0;//初始化

后面读取count就可以得到实例化的数目了,就是学生数目
推荐这个写法,因为你这里使用链表,最好自己写一个构造析构函数来申请释放资源。
复杂度也比遍历链表来的低。

遍历,只要下一个指针不是空就+1
或者自定义一个静态量,创一个链表+1,删-1

要解决这个问题,首先好好设计一下自己的数据结构,我认为应该是 Hash + linkedlist , 或者 array + linkedlist

问题解决了, 图片说明

可以定义一个函数如下:

int length(struct node *head)
{
    int num = 0;

    while (head != NULL)
    {
        num += 1;
        head = head->next;
    }

    return num;
}

假如 pStudent是你创建的结构体指针,输入完数据后,用

 int count = length(pStudent);

即可得到学生数量。