面试题答案
一键面试设计思路
- 结构体定义:
- 链表节点结构体需要包含一个联合体来存储不同类型的数据。同时,为了区分联合体中存储的数据类型,添加一个枚举类型成员。另外,链表节点还需要指向下一个节点的指针。
- 插入节点函数:
- 创建新节点,为联合体分配合适的数据类型,并设置枚举类型标识。然后将新节点插入到链表的合适位置(例如链表头部或尾部,这里以头部插入为例)。
- 查找节点函数:
- 遍历链表,根据传入的查找条件(例如查找特定字符串标识或数值),对比节点中联合体存储的数据。如果找到匹配的节点,则返回该节点指针;否则返回
NULL
。
- 遍历链表,根据传入的查找条件(例如查找特定字符串标识或数值),对比节点中联合体存储的数据。如果找到匹配的节点,则返回该节点指针;否则返回
- 联合体特性优化:
- 联合体共享内存空间,使得在同一时刻,节点只需存储一种类型的数据,从而优化了空间占用。在访问联合体成员时,根据枚举类型标识确定当前存储的数据类型,避免错误访问,提高操作效率。
核心代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义数据类型枚举
typedef enum {
TYPE_INT,
TYPE_DOUBLE,
TYPE_STRING
} DataType;
// 定义联合体存储不同类型数据
typedef union {
int intValue;
double doubleValue;
char stringValue[50];
} DataUnion;
// 定义链表节点结构体
typedef struct Node {
DataUnion data;
DataType dataType;
struct Node* next;
} Node;
// 插入节点到链表头部
Node* insertNode(Node* head, int intData) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data.intValue = intData;
newNode->dataType = TYPE_INT;
newNode->next = head;
return newNode;
}
Node* insertNode(Node* head, double doubleData) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data.doubleValue = doubleData;
newNode->dataType = TYPE_DOUBLE;
newNode->next = head;
return newNode;
}
Node* insertNode(Node* head, const char* stringData) {
Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->data.stringValue, stringData);
newNode->dataType = TYPE_STRING;
newNode->next = head;
return newNode;
}
// 查找节点函数
Node* findNode(Node* head, int intData) {
Node* current = head;
while (current != NULL) {
if (current->dataType == TYPE_INT && current->data.intValue == intData) {
return current;
}
current = current->next;
}
return NULL;
}
Node* findNode(Node* head, double doubleData) {
Node* current = head;
while (current != NULL) {
if (current->dataType == TYPE_DOUBLE && current->data.doubleValue == doubleData) {
return current;
}
current = current->next;
}
return NULL;
}
Node* findNode(Node* head, const char* stringData) {
Node* current = head;
while (current != NULL) {
if (current->dataType == TYPE_STRING && strcmp(current->data.stringValue, stringData) == 0) {
return current;
}
current = current->next;
}
return NULL;
}
以上代码展示了链表结构体定义、插入节点函数和查找节点函数的实现,利用联合体特性优化了空间占用和操作效率。在实际应用中,还需注意内存管理,例如在删除节点时释放相应的内存。