将项目添加到链接列表而不允许重复

我必须将项目添加到链接列表而不允许任何重复:

列表

typedef struct node { double info; struct node *next; } NODE; 

我的function:

  void addToEnd(NODE **lista, double info) { NODE *novi = (NODE *) malloc(sizeof(NODE)); novi->info = info; novi->next = NULL; if (*lista == NULL) *lista = novi; else { NODE *tmp = *lista; while (tmp->next) { if(tmp->info == info) {free(new); return;} tmp = tmp->next; } tmp->next = novi; } } 

它确实有效,如果数字不仅仅是彼此,例如添加5.5 1.0 5.5工作正常,但5.5 5.5 1.0添加5.5,是双舍入错误还是代码逻辑有缺陷?

  • 不要分配,直到你确定你确实需要内存
  • 避免特殊情况。 目标是在链中找到第一个(也是唯一的)NULL指针。 这可以是*lista (如果列表恰好是空的),或者是一些->next指针。

 void addToEnd(NODE **lista, double info) { NODE *new ; for ( ; *lista; lista = &(*lista)->next) { if((*lista)->info == info) return; } new = malloc(sizeof *new ); new->info = info; new->next = NULL; *lista = new; } 

或者,更紧凑(您不需要new指针,因为您可以使用->next指针):

 void addToEnd(NODE **lista, double info) { for ( ; *lista; lista = &(*lista)->next) { if((*lista)->info == info) return; } *lista = malloc(sizeof **lista); (*lista)->info = info; (*lista)->next = NULL; }