MST

星途 面试题库

面试题:C语言指针作为函数参数之复杂数据结构与回调函数

定义一个链表节点结构体,每个节点包含一个整数和一个指向下一个节点的指针。编写一个函数,该函数接受链表头指针和一个回调函数指针作为参数。回调函数用于对链表中的每个节点的整数值进行特定处理(例如平方运算)。在主函数中创建链表,调用上述函数,并输出处理后的链表节点值。
15.4万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
typedef struct ListNode {
    int val;
    struct ListNode *next;
} ListNode;

// 回调函数类型定义
typedef void (*Callback)(int*);

// 处理链表的函数
void processList(ListNode *head, Callback cb) {
    ListNode *current = head;
    while (current != NULL) {
        cb(&current->val);
        current = current->next;
    }
}

// 示例回调函数:平方运算
void square(int *num) {
    *num = *num * *num;
}

// 创建新节点的辅助函数
ListNode* createNode(int val) {
    ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
    newNode->val = val;
    newNode->next = NULL;
    return newNode;
}

// 主函数
int main() {
    // 创建链表 1 -> 2 -> 3
    ListNode *head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);

    // 调用处理链表的函数
    processList(head, square);

    // 输出处理后的链表节点值
    ListNode *current = head;
    while (current != NULL) {
        printf("%d ", current->val);
        current = current->next;
    }
    printf("\n");

    // 释放链表内存
    current = head;
    ListNode *next;
    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }

    return 0;
}

上述代码定义了链表节点结构体,实现了处理链表的函数 processList,它接受链表头指针和回调函数指针作为参数,在 main 函数中创建链表、调用处理函数并输出处理后的链表节点值。示例回调函数 square 对节点值进行平方运算。

如果是 C++ 代码:

#include <iostream>

// 定义链表节点结构体
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 回调函数类型定义
typedef void (*Callback)(int*);

// 处理链表的函数
void processList(ListNode *head, Callback cb) {
    ListNode *current = head;
    while (current != NULL) {
        cb(&current->val);
        current = current->next;
    }
}

// 示例回调函数:平方运算
void square(int *num) {
    *num = *num * *num;
}

// 主函数
int main() {
    // 创建链表 1 -> 2 -> 3
    ListNode *head = new ListNode(1);
    head->next = new ListNode(2);
    head->next->next = new ListNode(3);

    // 调用处理链表的函数
    processList(head, square);

    // 输出处理后的链表节点值
    ListNode *current = head;
    while (current != NULL) {
        std::cout << current->val << " ";
        current = current->next;
    }
    std::cout << std::endl;

    // 释放链表内存
    current = head;
    ListNode *next;
    while (current != NULL) {
        next = current->next;
        delete current;
        current = next;
    }

    return 0;
}

C++ 代码同样定义链表节点结构体,实现处理链表函数 processListmain 函数中创建链表、调用处理函数并输出处理后的链表节点值,示例回调函数 square 对节点值进行平方运算,同时注意了内存释放。