面试题答案
一键面试设计思路
- 内存分配:
- 首先为新节点分配内存。如果分配失败,直接返回错误码,因为后续操作依赖于节点的存在。
- 接着根据用户输入为节点中的动态数组分配内存。若数组内存分配失败,释放已分配的节点内存,然后返回错误码。
- 链表连接:
- 找到链表的合适位置(这里假设在链表头部插入),将新节点连接到链表中。
- 错误处理:
- 在任何内存分配步骤失败时,释放之前已分配的内存,确保没有内存泄漏,并返回相应错误码。
代码
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int *data; // 动态分配的数组
struct Node *next;
} Node;
// 插入新节点函数
int insertNode(Node **head, int size, int *values) {
// 分配新节点内存
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
return -1; // 节点内存分配失败
}
// 分配动态数组内存
newNode->data = (int *)malloc(size * sizeof(int));
if (newNode->data == NULL) {
free(newNode);
return -2; // 数组内存分配失败
}
// 复制数据到动态数组
for (int i = 0; i < size; i++) {
newNode->data[i] = values[i];
}
// 连接新节点到链表头部
newNode->next = *head;
*head = newNode;
return 0; // 成功
}
// 释放链表内存函数
void freeList(Node *head) {
Node *current = head;
Node *next;
while (current != NULL) {
next = current->next;
free(current->data);
free(current);
current = next;
}
}
// 测试代码
int main() {
Node *head = NULL;
int size = 3;
int values[] = {1, 2, 3};
int result = insertNode(&head, size, values);
if (result == 0) {
printf("Node inserted successfully.\n");
} else {
printf("Insertion failed with error code: %d\n", result);
}
freeList(head);
return 0;
}
以上代码用C语言实现,insertNode
函数实现了向链表插入新节点的功能,并且在内存分配失败时进行了恰当的错误处理和内存释放。freeList
函数用于释放整个链表的内存。main
函数用于测试插入节点的功能。