项目添加到链接列表,而不允许重复 [英] adding items to linked list without allowing duplicates
本文介绍了项目添加到链接列表,而不允许重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要补充项目链表没有使任何复制:
I have to add items to a linked list without allowing any duplicates:
列表
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 1.0增加了两个5.5的,它是一个双舍入误差或者是code逻辑有缺陷?
It does work if the numbers aren't just besides each other, for example adding 5.5 1.0 5.5 works fine, but 5.5 5.5 1.0 adds both of the 5.5, is it a double rounding error or is the code logic flawed ?
推荐答案
- 不得分配,直到你确信你实际需要的内存
- 避免特殊情况。我们的目标是找到的第一个(也是唯一一个)NULL链中的指针。这可以是
* LISTA
(如果该列表恰巧是空的),或者一些的 - >接下来
指针
- Don't allocate untill you are sure that you actually need the memory
- avoid special cases. The goal is to find the first (and only) NULL pointer in the chain. This can be
*lista
(if the list happens to be empty), or some of the->next
pointers.
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;
}
或者,更紧凑的(你不需要的新
指针,因为你可以使用 - >接下来
指针):
Or, even more compact (you don't need the new
pointer, since you can use the ->next
pointer ):
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;
}
这篇关于项目添加到链接列表,而不允许重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文