C 从链表中删除类似项
我注意到,在创建第一个重复检查后,下一个重复检查都指向同一个哺乳动物,所以当我调用great_circle计算两者之间的距离时,我得到一个0的列表,因为它是在比较同一个哺乳动物C 从链表中删除类似项,c,linked-list,C,Linked List,我注意到,在创建第一个重复检查后,下一个重复检查都指向同一个哺乳动物,所以当我调用great_circle计算两者之间的距离时,我得到一个0的列表,因为它是在比较同一个哺乳动物 void remove_duplicates() { int i,j; double distance; Mammal *next=head2.pointer; for(i=0;i<list_length2-1;i++) { Mammal *check=next->pointer; Dupli
void remove_duplicates() {
int i,j;
double distance;
Mammal *next=head2.pointer;
for(i=0;i<list_length2-1;i++) {
Mammal *check=next->pointer;
Duplicate *d=malloc(sizeof(Duplicate));
d->mampointer=NULL;
d->number_of=0;
for(j=0;j<(list_length2-i)-1;j++) {
distance=great_circle(next->location, check->location);
if(distance<=0.02 && next->species==check->species) {
Mammal *a=next;
Mammal *b=check;
a->pointer=d->mampointer;
d->mampointer=a;
b->pointer=d->mampointer;
d->mampointer=b;
d->number_of++;
d->number_of++;
}
printf("%f\n",distance);
if (check->pointer!=NULL) {
check=check->pointer;
}
}
if(d->mampointer!=NULL) {
add_duplicate(create_duplicate(d));
}
if (next->pointer!=NULL) {
next=next->pointer;
}
}
}
似乎check指向的是与next相同的内存,而next永远不会发生,check应该始终在next之后
编辑:我试图解决的问题是:
有几种哺乳动物有纬度和经度坐标
一些哺乳动物已经被报道过好几次,但坐标略有不同
我必须找到这些复制品,并用一只哺乳动物替换它们,用“错误”单词的平均值。看看这个链接:
这将帮助您遍历链接列表,而不需要像head2等冗余和混乱的指针
乍一看,Kozmik关于check->pointer应该是check->next的评论似乎是正确的,但是,再次尝试避免多余的指针,除非它使代码可读
我发现遍历链表的一种优雅方法是在cur\u node->next==NULL时停止,而不是允许“空”节点,并且必须检查cur\u node->next->item==NULL。我假设cur\u node->pointer引用的是存储在该节点中的项
例如:
typedef struct node_s {
void * item; // the item you are storing in this node
node_s * next; // the next node
} Node;
typedef struct list_s {
void * head;
/* maybe some extra info like size etc */
} List;
那么遍历就很容易了:
List * list = malloc(sizeof *list);
list->head = NULL;
/*
create your first node etc, add to list in the obvious way.
...
add more nodes
...
*/
//traversal
Node ** head = &list->head;
while (*head) { //we have a non-null node so keep going...
Node *cur_node = *head;
head = &cur_node->next;
/* do stuff with current node (even delete it!). */
}
这样做非常简单,只需两个指针就可以处理head和cur_节点。Q:删除重复项的算法是什么?你能解释一下代码应该做什么吗?问:什么是大圆?问:为什么要在删除重复项中添加重复项?问:您试图解决的问题到底是什么?请参阅编辑以了解更多信息。如果您能够真正清理代码,这将有所帮助。check->pointer您的命名法不应该是check->next,而应该是哺乳动物*mPointer,而不是哺乳动物*mPointer。如果距离物种==检查->物种应该是,如果距离物种==检查->物种是一种短路状态的方式,我还建议在这里设置更多的格式。什么是哺乳动物?什么是复制品?什么是添加副本?什么是复制?头2是什么?列表长度是多少?顺便说一句,这段代码看起来似乎需要一些认真的重构。