C 向升序链表中插入元素

C insert element into ascending linked list

我的插入方法有问题,因为某种原因我最终陷入无限循环。这是我的结构:

 struct List {
    char element;
    struct List *next;
 };

这是我的插入方法:

void insert(struct List *first, char el){
    struct List *new=NULL;
    struct List *current = first;
    new = (struct List*) malloc (sizeof(struct List));
    new->element = el;
    new->next = NULL;
    if (first == NULL){
        first = new;    
        return;
    }
    while (1){  //this loop never ends
        if (current->next == NULL) break;
        if (current->next->element < el){
            current = current->next;        
        }else{
            break;
        }
    }
    struct List *ex_next = current->next;
    current->next = new;
    new->next = ex_next;
}

我知道这里有类似的问题:C - Inserting into linked list in ascending order 但它并没有真正帮助我。

insert 的第一个参数是一个指针。但是你需要一个指向指针的指针(struct List **first)。

如果列表为空,则将 VALUE NULL 传递给函数(方法中的变量 first 的值为 NULL)。然后你给它分配一个新的 malloced 值和 return。调用方的变量没有改变,你的内存泄漏了。

当你传递一个指针的指针时,变量first保存调用方法的变量地址。这样,您可以重新分配它的值。

指针,指针的指针,函数数组指针的指针return函数指针....这就是 C 的有趣部分;)