c - 如何迭代节点列表并比较字符串

标签 c

我对 C 中链表的概念还很陌生。我花了很多时间想出一个逻辑来执行以下操作,但一切都是徒劳的。我正在尝试遍历链接列表。假设每个节点代表一个人,每个人(节点)有两个特征。例如:

struct person {
    struct person *next;
    char name[NAME_LENGTH];
    char trait_01[TRAIT_LENGTH];
    char trait_02[TRAIT_LENGTH];
}

Node 1: Sarah (trait 1: Soccer Trait 2: Designer)
Node 2: Carl (trait 1: Baseball Trait 2: None)
Node 3: Andrew (trait 1: Soccer Trait 2: Walking)
Node 4: John (trait 1: Cricket Trait 2: Designer)
Node 5: Cara (trait 1: Surfer Trait 2: Walking)
Node 6: Ben (trait 1: Racing Trait 2: Acting)
Node 7: Andy (trait 1: Walking Trait 2: Surfer) 
Node 8: Jack (trait 1: Designer trait 2: Soccer )

**Output:**
Soccer
Designer
Baseball
Walking
Cricket
Surfer
Racing 
Acting

输出没有重复任何特征,并且不包含“None”一词,并且应该按顺序排列,即先打印特征 1,然后打印特征 2。

有谁可以帮忙吗?

最佳答案

正如您在评论中提到的,逻辑不清楚,因为您的输出中没有任何证据表明trait1可以与trait2进行比较 为了识别重复的特征,承保代码只是从 trait1 中已出现的值中删除(而不是打印)重复的 trait1 值,并且与 相同特征2:

//AFTER CREATING THE LINKED-LIST

temp=head;             //temp is a temporary node for traversal
int indicator1=0;
int indicator2=0;

while(temp)
{
    temp1=head;       //temp1 is a temporary node 

    if(temp==head)   //all of the traits of head node is to printed with the "None" logic requirement of course
    {
        if(strcmp(temp->trait_01,"None")!=0)
            printf("%s\n",temp->trait_01);

        if(strcmp(temp->trait_02,"None")!=0)
            printf("%s\n",temp->trait_02);
    }
    else //if trait is already present in earlier nodes then it is not printed and of course "None" logic is followed
    {    
         while(temp1!=temp)
         {
             if((!strcmp(temp->trait_01,temp1->trait_01))&&(indicator1==0)&&(!strcmp(temp->trait_01,temp1->trait_02)))
             {
                 indicator1=1;
             }

             if((!strcmp(temp->trait_02,temp1->trait_02))&&(inicator2==0)&&(!strcmp(temp->trait_02,temp1->trait_01)))
             {
                 indicator2=1;
             }
         }
         if((indicator1==0)&&(strcmp(temp->trait_01,"None")))
             printf("%s\n",temp->trait_01);
         if((indicator2==0)&&(strcmp(temp->trait_02,"None")))
             printf("%s\n",temp->trait_01);

    }
    temp=temp->next;

    indicator1=0;
    indicator2=0;
}

解释:第一个 while 循环 while(temp) 遍历链表的每个节点(当 temp 时,违反了 while 条件是 NULL 即链表的末尾)。

第二个 while 循环 while(temp1!=temp) -> 代码尝试将 temp 节点的特征值与位于的节点的特征值进行匹配temp 之前的链表(head 节点和 temp 之间),temp1 表示位于 temp 之上/之后的节点code>head 节点和 temp 节点之前。

条件 !strcmp(str1, str2)v(当字符串相同时,strcmp 返回 0) 表示两个字符串是同样,if 条件将得到满足,并且 indicator 将设置为 1,表示特征值 temp节点(trait_01trait_02)相同 作为某个先前节点 temp1 的特征值。当此指示器设置为 1 时,我们不会打印特征值。

希望这有帮助!

关于c - 如何迭代节点列表并比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58900881/

相关文章:

c - fscanf 无法从 txt 文件读取数据

c - 如何在 Mac OS X 上设置 libusb?

C动态加载文件太短?

c - LLVM 解释器 (lli) 和共享对象加载

C结构问题

arrays - 结构体数组成员地址问题

c - 将二进制数据 append 到c中的文件

c - 如何在 C 中将字符串与结构一起使用?

c - 基于\0 终止的循环无法正常工作?

c - 构建VFML增量决策树切分故障