MST

星途 面试题库

面试题:C语言间接访问操作符在动态内存管理与复杂数据结构中的深度应用

设计一个链表结构,链表节点包含一个 `int` 类型的数据成员和一个指向下一个节点的指针。编写函数实现链表的创建、插入节点、删除节点操作,在这些函数中必须合理使用间接访问操作符。特别地,要求在插入节点函数中,使用间接访问操作符来处理可能出现的内存分配失败情况,并在删除节点函数中确保正确释放内存。请写出完整的C语言代码,包括必要的头文件、结构体定义以及所有函数的实现。
12.4万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#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;
}