2013-11-25 47 views
0

我做了一个链表是这样的:如何比较C中链接列表中的每个项目?

typedef struct { 
    char *id; 
    char *nombre; 
    char *region; 
    char *partido; 
    int edad; 
    struct votante *siguiente; 
} votante; 

而且我有一个创建从一个文本文件中读取一些数据新节点的功能。问题是,我必须寻找具有相同ID但拥有不同“partido”(派对,就像政治派对)的人。但是当我移动到列表中时,我无法显示该信息。我有一个代码沿着整个列表移动,并将X位置与X右侧的另一个位置进行比较。问题是,信息重复出现,因为我正在搜索检查我的两个条件的每种可能的组合。我想我应该删除一个节点后,我检查它,以避免这种情况,并保留每个删除的节点在另一个列表中只有被删除的人,但我不知道如何实现这一点。 这里是我的功能:

votante *consultarDobleRegistro(votante *lista){ 
    votante *aux = lista; 
    votante *aux2 = aux->siguiente; 
    votante *eliminar; 
    votante *fraudes = crearVotante(); 
    int encontrar = 0; 
    int vueltas = 0; 

    while(aux->siguiente != NULL){ 
     //si existe el mismo ID en diferentes partidos 
     if(strcmp(aux->id, aux2->id) == 0 && strcmp(aux->partido, aux2->partido) != 0){ 
      // agrego a "fraudes" el resultado que está después del parámetro a comparar 
      encontrar++; 
      if(encontrar==1){ 
       printf("encontro aux: %s - %s\n", aux->id, aux->partido); 
      } 
      printf("encontro aux2: %s - %s\n", aux2->id, aux2->partido); 
      fraudes = agregarNodo(fraudes, aux2->id, aux2->nombre, aux2->region, aux2->partido, aux2->edad); 
      if(aux2->siguiente == NULL){ 
       aux = aux->siguiente; 
       aux2 = aux->siguiente; 
      } else { 
       aux2 = aux2->siguiente; 
      } 
     } else { 
      if(aux2->siguiente == NULL){ 
       aux = aux->siguiente; 
       encontrar = 0; 
       vueltas++; 
       aux2 = aux->siguiente; 
      } else { 
       aux2 = aux2->siguiente; 
      } 
     } 
    } 
    printf("vueltas: %d\n", vueltas); 
    return fraudes; 
} 

我需要表现出与相同的“ID”和而不同“党”的节点(或让他们进入一个新的列表,以便我可以用我的节目()函数来显示他们后来)。

+0

您应该收到有关类型不匹配的编译器警告。 'siguiente'字段不指向显示的结构类型。你需要'typedef struct votante {...} votante;'或者等价的。注意结构标签;这是至关重要的。 –

+0

你的问题意味着只要他们也有相同的'partido',就有两个记录具有相同的'id'。这是你真正的意思吗?或者'id'值应该在列表中唯一吗? –

回答

1

您提供的代码未显示主要问题。
根据你的描述,你应该关注的是你如何旅行和比较整个列表。
我不是在算法非常好,因此该解决方案可能不会非常的效率,但希望提供一些基本思路:
的主要目的是进行分类标识,具有新的链表结构是这样的:

struct votante_same_id { 
    struct votante *id_group; 
    struct votante_same_id *next; 
}; 

struct votante_id_group { 
    char *id; 
    struct votante_same_id head; 
    struct votante_id_group *next; 
}; 

然后,您将旅行整个votante名单,比较每个id与votante_id_group->编号,
当一个新的id被发现,将它添加到votante_id_group;否则将该表添加到现有的votante_same_id列表中。
当旅行结束时,现在你旅行votante_id_group,然后分类partido,类似于上面。
最后votante节点在不同的列表中应该是你需要的。

相关问题