C语言链表查找字符串:高效实现代码示例
以下是使用C语言实现的代码:\n\nc\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct list_s {\n char *data;\n struct list_s *next;\n} list_t;\n\nint find_list_str(list_t *list, char *str) {\n list_t *current = list;\n \n while (current != NULL) {\n if (strcmp(current->data, str) == 0) {\n return 1; // 目标字符串存在于链表中\n }\n current = current->next;\n }\n \n return 0; // 目标字符串不存在于链表中\n}\n\nint main() {\n // 创建链表\n list_t *head = (list_t *)malloc(sizeof(list_t));\n head->data = "Hello";\n head->next = (list_t *)malloc(sizeof(list_t));\n head->next->data = "World";\n head->next->next = NULL;\n \n // 调用函数进行匹配\n int result = find_list_str(head, "World");\n \n if (result == 1) {\n printf("目标字符串存在于链表中\n");\n } else {\n printf("目标字符串不存在于链表中\n");\n }\n \n // 释放链表内存\n list_t *current = head;\n list_t *next;\n \n while (current != NULL) {\n next = current->next;\n free(current);\n current = next;\n }\n \n return 0;\n}\n\n\n在上述代码中,首先定义了一个名为list_s的结构体,它包含一个char*类型的data成员和一个指向下一个节点的指针next。然后使用typedef关键字将struct list_s重命名为list_t,以方便使用。\n\n接下来,定义了一个find_list_str函数,该函数接受一个指向链表头部的指针list和一个目标字符串str作为参数。在函数中,使用一个循环遍历链表的每个节点,将节点的data成员与目标字符串进行比较。如果找到匹配的字符串,则返回1;如果遍历完整个链表后仍未找到匹配的字符串,则返回0。\n\n在main函数中,首先创建了一个包含两个节点的链表。然后调用find_list_str函数,将链表头部指针和目标字符串作为参数,获取匹配结果。最后,根据返回值输出相应的结果。最后,释放链表所占用的内存。\n\n注意:上述代码仅为示例,实际使用时需要根据需求进行相应的修改和扩展。
原文地址: https://www.cveoy.top/t/topic/pKd0 著作权归作者所有。请勿转载和采集!