c - 如何比较C中链表中的每个项目?

标签 c search linked-list compare

我制作了一个像这样的链接列表:

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”但不同“partido”的节点(或者将它们放入一个新列表中,以便我可以使用我的 show() 函数稍后显示它们)。

最佳答案

您提供的代码没有显示主要问题。
根据您的描述,您应该关注的是您的出行方式以及整个列表的比较。
我不太擅长算法,所以解决方案可能效率不是很高,但希望提供一些基本想法:
主要目的是对 id 进行分类,具有新的链表结构,如下所示:

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 进行比较,
当找到新的 id 时,将其添加到 votante_id_group 中;否则将该 votante 添加到现有的 votante_same_id 列表中。
当votante的旅行结束后,现在旅行votante_id_group,然后对partido进行分类,类似上面。
最后,不同列表中的 votante 节点应该就是您所需要的。

关于c - 如何比较C中链表中的每个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20183555/

相关文章:

c - 我应该使用 printf ("\n") 还是 putchar ('\n' ) 在 C 中打印换行符?

node.js - Mongoose 文本搜索 - 将其行为更改为 AND 操作会减慢速度

c - 当正数在前时对链表进行排序

mysql - 搜索查询优化

c++ - 使用链表实现错误队列

python - 如何检查项目是否在链接列表中?

c - 提取 proc/status linux 文件的一部分

c - 在 Haskell 中键入 : Passing a number that looks fractional, 但始终是整数(类型别名)

c - mach_vm_region 与 mach_vm_region_recurse

search - Tiddlywiki : make a list of all tiddlers tagged with name of current tiddler