简体   繁体   English

C将元素插入升序链表

[英]C insert element into ascending linked list

I have problems with my insert method, as for some reason I end up with infinite loop. 我的insert方法遇到问题,由于某种原因,我最终陷入无限循环。 Here is my struct: 这是我的结构:

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

And here is my insert method: 这是我的插入方法:

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;
}

I am aware of similar question here: C - Inserting into linked list in ascending order but it didn't really help me. 我在这里知道类似的问题: C-按升序插入到链表中,但这并没有真正帮助我。

The first argument to insert is a pointer. insert的第一个参数是一个指针。 But you need a pointer to a pointer ( struct List **first ). 但是您需要一个指向指针的指针( struct List **first )。

If the list is empty, you pass the VALUE NULL into the function (the variable first inside the method have the value NULL). 如果该列表是空的,你传递NULL 插入函数(变量first方法里面有NULL值)。 Then you assign a new malloced value to it and return. 然后,给它分配一个新的malloced值并返回。 The variable on the calling side haven't changed and your memory leaked. 调用方的变量未更改,并且内存泄漏。

When you pass a pointer of a pointer, the variable first holds the address of the variable of the calling method. 当您传递指针的指针时,该变量first保存调用方法的变量的地址。 This way, you can reassign it's value. 这样,您可以重新分配其价值。

Pointers, Pointers of Pointers, Pointers of Pointers of arrays of functions returning function pointers .... thats the fun part of C ;) 指针,指针的指针,返回函数指针的函数数组的指针....多数民众赞成在C的乐趣部分;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM