struct list_head

#include "list.h"
#include 

typedef struct {
    struct list_head  list;
} lgst_df_set_t;

typedef struct {
    int B;
    struct list_head slist;
} df_file;

#define LGST_GET_MIN_BENEFIT(set)  \
    list_entry(set.list.next, typeof(df_file), slist)

#define LGST_GET_MAX_BENEFIT(set)  \
    list_entry(set.list.prev, typeof(df_file), slist)

lgst_df_set_t set;

struct list_head *
lgst_find_first_min_B(df_file* df, lgst_df_set_t *set)
{
    df_file *cur = NULL;

    list_for_each_entry(cur, &set->list, slist) {
        if (cur->B > df->B) {
            return cur->slist.prev; // 返回前驱
        }
    }

    return NULL;
}

void travel_list(lgst_df_set_t *set)
{
    df_file *cur  = NULL;
    list_for_each_entry(cur, &set->list, slist) {
        printf("%d, ", cur->B);
    }
}

void list_sort_add(struct list_head *p, struct list_head *new)
{
    new->prev = p;
    new->next = p->next;
    p->next->prev = new;
    p->next = new;
}

void insert_node(df_file* df)
{
    struct list_head *insert_pos = lgst_find_first_min_B(df, &set);
    if (!insert_pos) {
        list_add_tail(&df->slist,&set.list);
    } else 
        list_sort_add(insert_pos, &df->slist);

    printf("插入%d: ", df->B);
    travel_list(&set);
    printf("\n");
}

int main() 
{
    INIT_LIST_HEAD(&set.list);
    
    df_file df1;
    df_file df2;
    df_file df3;
    df_file df4;
    df_file df5;
    df_file df6;
    
    df1.B = 1;
    INIT_LIST_HEAD(&df1.slist);
    df2.B = 2;
    INIT_LIST_HEAD(&df2.slist);
    df3.B = 2;
    INIT_LIST_HEAD(&df3.slist);
    df4.B = 3;
    INIT_LIST_HEAD(&df4.slist);
    df5.B = 0;
    INIT_LIST_HEAD(&df5.slist);
    df6.B = -1;
    INIT_LIST_HEAD(&df6.slist);
    
    insert_node(&df2);
    insert_node(&df1);
    insert_node(&df3);
    insert_node(&df4);
    insert_node(&df5);
    insert_node(&df6);
    
    df_file* entry_min = LGST_GET_MIN_BENEFIT(set);
    df_file* entry_max = LGST_GET_MAX_BENEFIT(set);
    printf("min:%d, max:%d", entry_min->B, entry_max->B);
}

你可能感兴趣的:(struct list_head)