static GList * g_list_sort_real (GList *list, GFunc compare_func, gpointer user_data) { GList *l1, *l2; if (!list) return NULL; if (!list->next) return list; l1 = list; l2 = list->next; while ((l2 = l2->next) != NULL) { if ((l2 = l2->next) == NULL) break; l1 = l1->next; } l2 = l1->next; l1->next = NULL; return g_list_sort_merge (g_list_sort_real (list, compare_func, user_data), g_list_sort_real (l2, compare_func, user_data), compare_func, user_data); }
/*将链表按照参数中设定比较方式排序*/ static GList* g_list_sort_real (GList *list, GFunc compare_func, gpointer user_data) { GList *l1, *l2; if (!list) return NULL; if (!list->next) return list; /*将链表L拆成前后两半,分别由L1与L2所指*/ l1 = list; l2 = list->next; while ((l2 = l2->next) != NULL) { if ((l2 = l2->next) == NULL) break; l1 = l1->next; } l2 = l1->next; l1->next = NULL; /*递归的方式处理两段子链表,实现整个链表按照参数中的比较方式排序*/ return g_list_sort_merge (g_list_sort_real (list, compare_func, user_data), g_list_sort_real (l2, compare_func, user_data), compare_func, user_data); }
/** * GCompareDataFunc: * @a: a value * @b: a value to compare with * @user_data: user data * * Specifies the type of a comparison function used to compare two * values. The function should return a negative integer if the first * value comes before the second, 0 if they are equal, or a positive * integer if the first value comes after the second. * * Returns: negative value if @a < @b; zero if @a = @b; positive * value if @a > @b */ GList * g_list_sort_with_data (GList *list, GCompareDataFunc compare_func, gpointer user_data) { return g_list_sort_real (list, (GFunc) compare_func, user_data); }
/*将链表按照参数中设定比较方式排序*/ GList * g_list_sort (GList *list, GCompareFunc compare_func) { return g_list_sort_real (list, (GFunc) compare_func, NULL); }