面试题答案
一键面试#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(¤t->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(¤t->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++ 代码同样定义链表节点结构体,实现处理链表函数 processList
,main
函数中创建链表、调用处理函数并输出处理后的链表节点值,示例回调函数 square
对节点值进行平方运算,同时注意了内存释放。