吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C中的通用链表

C中的通用链表

来源:网络 | 更新时间:2022-01-18 19:47:14
C++Java不同,C不支持泛型。如何在 C 中创建可用于任何数据类型的链表?在 C 中,我们可以使用void 指针和函数指针来实现相同的功能。void 指针的伟大之处在于它可以用来指向任何数据类型。此外,所有类型的指针的大小总是相同的,所以我们总是可以分配一个链表节点。需要函数指针来处理存储在 void 指针指向的地址处的实际内容。  以下是演示通用链表工作的示例 C 代码。
// C program for generic linked list
#include<stdio.h>
#include<stdlib.h>

/* A linked list node */
struct Node
{
// Any data type can be stored in this node
void *data;

struct Node *next;
};

/* Function to add a node at the beginning of Linked List.
This function expects a pointer to the data to be added
and size of the data type */
void push(struct Node** head_ref, void *new_data, size_t data_size)
{
// Allocate memory for node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

new_node->data = malloc(data_size);
new_node->next = (*head_ref);

// Copy contents of new_data to newly allocated memory.
// Assumption: char takes 1 byte.
int i;
for (i=0; i<data_size; i++)
*(char *)(new_node->data + i) = *(char *)(new_data + i);

// Change head pointer as new node is added at the beginning
(*head_ref) = new_node;
}

/* Function to print nodes in a given linked list. fpitr is used
to access the function to be used for printing current node data.
Note that different data types need different specifier in printf() */
void printList(struct Node *node, void (*fptr)(void *))
{
while (node != NULL)
{
(*fptr)(node->data);
node = node->next;
}
}

// Function to print an integer
void printInt(void *n)
{
printf(" %d", *(int *)n);
}

// Function to print a float
void printFloat(void *f)
{
printf(" %f", *(float *)f);
}

/* Driver program to test above function */
int main()
{
struct Node *start = NULL;

// Create and print an int linked list
unsigned int_size = sizeof(int);
int arr[] = {10, 20, 30, 40, 50}, i;
for (i=4; i>=0; i--)
push(&start, &arr[i], int_size);
printf("Created integer linked list is n");
printList(start, printInt);

// Create and print a float linked list
unsigned float_size = sizeof(float);
start = NULL;
float arr2[] = {10.1, 20.2, 30.3, 40.4, 50.5};
for (i=4; i>=0; i--)
push(&start, &arr2[i], float_size);
printf("nnCreated float linked list is n");
printList(start, printFloat);

return 0;
}
输出: 
Created integer linked list is
 10 20 30 40 50

Created float linked list is
 10.100000 20.200001 30.299999 40.400002 50.500000
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com