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

时间:2015-11-08 15:50:49

标签: c sorting linked-list

我希望了解如何在插入时实现排序链表?下面是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;
}

1 个答案:

答案 0 :(得分:0)

这很简单。如果要插入排序列表。然后在插入列表之前,您必须遍历列表,直到您转到列表末尾或找到大于当前列表值的节点值。然后插入您的列表。