从链接列表中删除类似的项目

时间:2014-12-12 03:23:31

标签: c linked-list

我注意到在创建它之后第一次重复检查,然后两者都指向同一个哺乳动物,所以当我打电话给great_circle时,两者之间的距离变得很大,我得到一个0&#39的列表因为它比较了同一个哺乳动物。

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;
    } 
}
}

检查似乎指向与下一个应该永远不会发生的内存相同的内存,检查应始终在下一个之后。

编辑:我试图解决的问题是:

有几种哺乳动物的纬度和经度坐标,

有些哺乳动物已被报告过几次,但坐标略有不同,

我必须找到这些副本,并用一个哺乳动物取代它们,并且平均值为“错误”。共ORDS。

1 个答案:

答案 0 :(得分:0)

请看一下这个链接:http://www.cprogramdevelop.com/2252274/ 这将帮助您遍历链接列表,而无需冗余(和令人困惑)指针,如head2等。

首先看来Kozmik的评论是正确的,check->pointer应该是check->next - 但是,再次尝试避免冗余指针,除非它使代码可读。

我发现遍历链表的优雅方法是在cur_node->next == NULL停止而不是允许“空”节点并且必须检查是否cur_node->next->item == NULL(我假设cur_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!). */
}

这种方式非常简单,只需要担心两个指针(headcur_node)。

相关问题