2013-11-25 48 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節點在不同的列表中應該是你需要的。

相關問題