更多资料请关注微信公众号:Linux兵工厂
函数指针(Function Pointers):
函数指针是指向函数的指针变量。它可以用于存储函数的地址,以便在程序运行时动态调用函数。以下是一些函数指针的基本操作:
-
声明和初始化函数指针:
#include <stdio.h> // 声明一个函数指针类型 typedef int (*Operation)(int, int); // 定义两个函数 int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int main() { // 声明并初始化函数指针 Operation operationPtr = add; // 使用函数指针调用函数 int result = operationPtr(5, 3); printf("Result: %d\n", result); // 修改函数指针指向的函数 operationPtr = subtract; result = operationPtr(5, 3); printf("Result: %d\n", result); return 0; }
-
函数指针作为函数参数:
#include <stdio.h> // 定义一个函数指针类型 typedef int (*Operation)(int, int); // 定义一个接受函数指针作为参数的函数 int calculate(Operation operation, int a, int b) { return operation(a, b); } // 定义两个函数 int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int main() { // 使用函数指针作为参数调用函数 printf("Result (Addition): %d\n", calculate(add, 5, 3)); printf("Result (Subtraction): %d\n", calculate(subtract, 5, 3)); return 0; }
链表(Linked List):
链表是一种常见的数据结构,它由节点组成,每个节点包含数据和一个指向下一个节点的指针。链表可以动态地分配内存,具有插入和删除节点的高效性。以下是链表的基本操作:
-
链表节点的定义:
#include <stdio.h> #include <stdlib.h> // 定义链表节点结构 struct Node { int data; struct Node *next; };
-
创建和初始化链表:
// 创建链表节点 struct Node *createNode(int data) { struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); if (newNode != NULL) { newNode->data = data; newNode->next = NULL; } return newNode; } // 初始化链表头 struct Node *initializeList(int data) { return createNode(data); }
-
插入节点:
// 在链表尾部插入节点 void insertNode(struct Node *head, int data) { struct Node *current = head; while (current->next != NULL) { current = current->next; } struct Node *newNode = createNode(data); if (newNode != NULL) { current->next = newNode; } }
-
遍历链表:
// 遍历链表并打印节点数据 void traverseList(struct Node *head) { struct Node *current = head; while (current != NULL) { printf("%d -> ", current->data); current = current->next; } printf("NULL\n"); }
-
删除节点:
// 删除链表中的指定节点 void deleteNode(struct Node *head, int data) { struct Node *current = head; struct Node *prev = NULL; while (current != NULL && current->data != data) { prev = current; current = current->next; } if (current != NULL) { if (prev != NULL) { prev->next = current->next; free(current); } else { // 如果要删除的是头节点 head = current->next; free(current); } } }
这是链表和函数指针在C语言中的基本使用。链表是一种非常灵活的数据结构,适用于需要频繁插入和删除操作的场景。函数指针则提供了动态调用函数的机制,常用于实现回调函数等场景。