面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建链表函数
Node* createList(int value) {
Node *newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
return NULL;
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 插入节点函数
void insertNode(Node **head, int value, int position) {
Node *newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("内存分配失败\n");
return;
}
newNode->data = value;
newNode->next = NULL;
if (position == 1) {
newNode->next = *head;
*head = newNode;
return;
}
Node *current = *head;
for (int i = 1; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current == NULL) {
printf("位置无效\n");
free(newNode);
return;
}
newNode->next = current->next;
current->next = newNode;
}
// 删除节点函数
void deleteNode(Node **head, int position) {
if (*head == NULL) {
printf("链表为空\n");
return;
}
Node *temp = *head;
if (position == 1) {
*head = temp->next;
free(temp);
return;
}
for (int i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL || temp->next == NULL) {
printf("位置无效\n");
return;
}
Node *toDelete = temp->next;
temp->next = toDelete->next;
free(toDelete);
}
// 打印链表函数
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
// 释放链表内存函数
void freeList(Node *head) {
Node *current = head;
Node *nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
}
你可以通过以下方式调用这些函数:
int main() {
Node *head = createList(10);
printList(head);
insertNode(&head, 20, 2);
insertNode(&head, 30, 3);
printList(head);
deleteNode(&head, 2);
printList(head);
freeList(head);
return 0;
}