我正在尝试创建一个基于两个变量进行排序插入的函数,首先是level
(数字)& name
(按字母顺序)。
显然我有一些逻辑错误。
我的链表结构:
struct node {
struct node *next;
int level;
char *name;
};
我的字符串比较功能:
int compare(struct node *one, struct node *two)
{
return strcmp(one->name, two->name);
}
我的插入功能:
void insert(struct node **head, const int level, char *name, int(*cmp)(struct node *l, struct node *r))
{
struct node *new;
new = malloc(sizeof *new);
new->level = level;
new->name = name;
/* Find the insertion point */
for (; *head != NULL; head = &(*head)->next)
{
if ((*head)->level > level) {
if (cmp(*head, new) > 0)
break;
}
}
new->next = *head;
*head = new;
}
示例输入:
insert(&root, 1, "A", compare);
insert(&root, 1, "C", compare);
insert(&root, 1, "B", compare);
insert(&root, 3, "B", compare);
insert(&root, 2, "Z", compare);
insert(&root, 1, "A", compare);
insert(&root, 1, "C", compare);
insert(&root, 1, "B", compare);
insert(&root, 3, "B", compare);
insert(&root, 2, "Z", compare);
结果:
1 A
1 C
1 B
1 A
3 B
1 C
1 B
2 Z
3 B
2 Z