面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
typedef struct Node* NodePtr;
struct Node {
int data;
NodePtr next;
};
// 创建链表
NodePtr createList(int value) {
NodePtr newNode = (NodePtr)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("内存分配失败\n");
return NULL;
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 在指定位置插入节点
NodePtr insertNode(NodePtr head, int value, int position) {
NodePtr newNode = (NodePtr)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("内存分配失败\n");
return head;
}
newNode->data = value;
newNode->next = NULL;
if (position == 0) {
newNode->next = head;
return newNode;
}
NodePtr current = head;
int count = 0;
while (current != NULL && count < position - 1) {
current = current->next;
count++;
}
if (current == NULL) {
printf("位置无效,无法插入\n");
free(newNode);
return head;
}
newNode->next = current->next;
current->next = newNode;
return head;
}
// 删除指定值的节点
NodePtr deleteNode(NodePtr head, int value) {
NodePtr current = head;
NodePtr prev = NULL;
if (current != NULL && current->data == value) {
head = current->next;
free(current);
return head;
}
while (current != NULL && current->data != value) {
prev = current;
current = current->next;
}
if (current == NULL) {
printf("值为 %d 的节点未找到\n", value);
return head;
}
prev->next = current->next;
free(current);
return head;
}
// 打印链表
void printList(NodePtr head) {
NodePtr current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
// 释放链表内存
void freeList(NodePtr head) {
NodePtr current = head;
NodePtr nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
}
int main() {
NodePtr head = createList(1);
if (head == NULL) return 1;
printList(head);
head = insertNode(head, 2, 1);
head = insertNode(head, 3, 2);
printList(head);
head = deleteNode(head, 2);
printList(head);
freeList(head);
return 0;
}
上述代码定义了链表节点,并实现了链表的创建、插入节点和删除节点功能,同时在各个函数中考虑了边界情况。createList
用于创建链表头节点,insertNode
在指定位置插入新节点,deleteNode
删除指定值的节点。printList
用于打印链表,freeList
用于释放链表占用的内存。