2015-11-19 85 views
0

我的插入方法有问题,因为某些原因导致无限循环。这里是我的结构:C将元素插入到升序链接列表中

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但它并没有真正帮助我。

+1

那么,这个循环会重复永远的唯一方法是,如果你有一个循环链接(即'node == node-> next')。 –

回答

3

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

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

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

指针,指针的指针,指针指针的函数返回函数指针数组的....这就是C的乐趣的一部分;)