C-插入时对链表进行排序



我想获得一些帮助,了解如何在插入点实现排序链表?下面是一个addItem函数,可以在列表的开头或末尾添加选项。例如,是否可以根据var.number;中给定的值进行插入(从而排序)?

struct structName {
    int number;
    int number2;
    char aString;
    struct structName *next;
};
struct structName *head = NULL;
struct structName *curr = NULL;
struct structName *element = NULL;
struct Struct var;
struct structName* addItem(struct structName var, bool appendList) {
    struct structName *pointer = (struct structName*)malloc(sizeof(struct structName));
    pointer->someString = var.aString;
    pointer->aNumber = var.number2;
    pointer->anotherNumber = var.number;
    pointer->next = NULL;
    if(appendList) {
        curr->next = pointer;
        curr = pointer;
    }
    else {
        pointer->next = head;
        head = pointer;
    }  
    return pointer;
}
这很简单。如果您想插入到排序列表中。然后,在插入列表之前,您必须遍历列表,直到到达列表的末尾或找到一个大于当前列表值的节点值。然后插入您的列表。

相关内容

  • 没有找到相关文章