C语言 在链表中排序插入



我试图创建一个基于两个变量levelname排序插入的函数。显然我有一些逻辑和语法错误。

我的链表结构:
struct node {
    struct node *next;
    int level;
    char name;
};

My string compare function:

int compare(struct node *one, struct node *two)
{
    return strcmp(one->name, two->name);
}

我的插入函数:

void insert(struct node **head, const int level, const char name, int(*cmp)(struct node *l, struct node *r))
{
    struct node *new =NULL;
    /* Find the insertion point */
    for (; *head; head = &(*head)->next)
    {
        if ((*head)->level > level) {     // I think this is what is causing the issue
            if (compare(*head, new) > 0)
            break;
        }
    }
    new = malloc(sizeof *new);
    new->level = level;
    new->name = name;
    new->next = *head;
    *head = new;
}

,这是调用堆栈:

insert(node **head, const int level, const char name, int(*)(node *, node *))

你的语法错误是这一行:

return strcmp(one->name, two->name);

函数strcmp期望两个char*(又名char指针),但你给它两个char

问题是……

char name;

char* name;

这对正确使用compare很重要。

此外,您需要重新安排insert函数,以便在使用它之前创建新节点。比如:

void insert(struct node **head, const int level, const char name, int(*cmp)(struct node *l, struct node *r))
{
    struct node *new =NULL;
    // Create and initialize new....
    new = malloc(sizeof *new);
    new->level = level;
    new->name = name;
    /* Find the insertion point */
    for (; *head; head = &(*head)->next)
    {
        if ((*head)->level > level) {     // I think this is what is causing the issue
            if (cmp(*head, new) > 0)
                        // ^^^ So that you can use it here
            break;
        }
    }
    new->next = *head;
    *head = new;
}

您正在将NULL值传递给cmp函数(?!?可能正确的函数是int compare(…)。在将new变量传递给函数之前,请尝试初始化该变量的值。

您声明node.namechar类型,但是您的比较函数被编写为好像它们是char的空终止数组或指向此类数组的指针(即C字符串)。您似乎想要这样做:

struct node {
    struct node *next;
    int level;
    char *name;
};

或者这个:

struct node {
    struct node *next;
    int level;
    char name[MY_MAXIMUM_NAME_LENGTH_PLUS_ONE];
};

此外,您的insert()函数将NULL指针传递给比较函数作为其第二个参数,因为您从未为指针new分配任何内存,当然,也从未为不存在的成员赋值。这根本说不通。你觉得你在拿什么做比较?你似乎想要这样的东西:

struct node *new = malloc(sizeof *new);
if (!new) {
    // allocation failure -- abort ...
}
new->level = level;
new->name = /* hmmmm ... */;

当然,这里也会出现名称类型的问题。

最新更新