您的位置:首页 > 其它

C和指针之高级指针话题通过函数指针实现在链表中找到特定的值

2017-12-06 02:00 405 查看

1、问题

通过函数指针实现在链表中找到特定的值,这里可以是int 类型或者char *类型
思路:
     整形数据自己写比较函数,字符串比较用strcmp,然后把这个函数指针传递到函数作为参数。



2、代码实现

#include <stdio.h>
#include <string.h>

typedef struct Node
{
struct Node *next;
char value[100];
//int value;
} Node;

//在链表中查找找到制定的值
Node *search_list(Node *node, void const *value, int (*compare)(void const *, void const *))
{
while (node != NULL)
{
if (compare(&(node->value), value) == 0)
{
printf("hello");
return node;
}
node = node->next;
}
return NULL;
}

int compare_int(void const *a, void const *b)
{
if (*(int *)a == *(int *)b)
return 0;
else
return 1;
}

int main()
{
Node node1, node2, node3, node4, node5;
strcpy(node1.value, "chenyu");
strcpy(node2.value, "chenxuan");
strcpy(node3.value, "chencaifeng");
strcpy(node4.value, "chenzixuan");
strcpy(node5.value, "chenzixi");
/**
node1.value = 1;
node2.value = 2;
node3.value = 3;
node4.value = 4;
**/
node1.next = &node2;
node2.next = &node3;
node3.next = &node4;
node4.next = &node5;
node5.next = NULL;

const char *value = "chenxuan";
Node *new_node = search_list(&node1, value, strcmp);
if (new_node != NULL)
printf("new_node value is %s\n", new_node->value);
else
printf("new_node is NULL\n");
/**
int  value = 4;;
Node *new_node = search_list(&node1, *value, compare_int);
if (new_node != NULL)
printf("new_node value is %d\n", new_node->value);
else
printf("new_node is NULL\n");
**/
return 0;
}




3、运行结果

1111deMacBook-Pro:malloc a1111$ gcc -g -w search_list.c -o search_list
1111deMacBook-Pro:malloc a1111$ ./search_list
hellonew_node value is chenxuan
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐