我必须在不允许任何重复项的情况下将项添加到链接列表:
名单
typedef struct node
{
double info;
struct node *next;
} NODE;
我的职能:
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.5 1.0同时添加了5.5,这是双舍入错误还是代码逻辑有缺陷?
最佳答案
在你确定你确实需要内存之前不要分配
避免特殊情况。目标是找到链中的第一个(也是唯一的)空指针。这可以是*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;
}
关于c - 将项目添加到链接列表,但不允许重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36824013/