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