weixin_45807699 2021-06-23 12:10 采纳率: 100%
浏览 60
已采纳

求用c语言或者c++写出来的完整代码

有大佬能帮忙写出来的吗  用c写

  • 写回答

1条回答 默认 最新

  • yangxr1995 2021-06-23 16:11
    关注

    因为最大月份和每月最大日期固定,所以可用二维数组,数组元素为链表头,hash冲突则将其头插到相同链表 

    #include <stdio.h>
    #include <assert.h>
    #include <stdlib.h>
    
    #define MON_MAX  12
    #define DAY_MAX  31
    
    struct hash_elemt {
        struct hash_elemt *list;
        struct stu *stu;
    } *buckets[MON_MAX+1][DAY_MAX+1];
    
    struct stu {
            char *name;
    };
    
    static struct hash_elemt **hash(int mon, int day)
    {
        assert(mon > 0 && mon <= MON_MAX);
        assert(day > 0 && day <= DAY_MAX);
        return &buckets[mon][day];
    }
    
    struct hash_elemt *hash_add(struct stu *stu, int mon, int day)
    {
        struct hash_elemt **phead, *new;
        phead = hash(mon, day);
        new = malloc(sizeof(struct hash_elemt));
        new->stu = stu;
        new->list = (*phead);
        (*phead) = new;
        return new;
    }
    
    void print_stu(struct stu *stu)
    {
            printf("stu : %s\n", stu->name);
    }
    
    void print_comm_stu(int mon, int day)
    {
        struct hash_elemt **phead,*e;
        printf("mon(%d), day(%d): \n", mon, day);
        phead = hash(mon,day);
        for (e = *phead; e; e= e->list)
            print_stu(e->stu);
    }
    
    int main()
    {
            struct stu s1, s2, s3, s4, s5;
            s1.name = "aa";
            s2.name = "bb";
            s3.name = "cc";
            s4.name = "dd";
            s5.name = "ee";
    
            hash_add(&s1, 1, 1);
            hash_add(&s2, 1, 1);
            hash_add(&s3, 1, 1);
            hash_add(&s4, 2, 1);
            hash_add(&s5, 2, 1);
    
            print_comm_stu(1, 1);
            print_comm_stu(2, 1);
    
            return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?