MST

星途 面试题库

面试题:C语言指针表达式在内存管理与数据结构中的深度应用

设计并实现一个简单的链表结构,链表节点包含一个 `int` 类型数据和一个指向下一节点的指针。要求通过指针表达式实现以下功能:1. 编写一个函数 `void insertNode(struct Node **head, int value)` 用于在链表头部插入新节点;2. 编写一个函数 `void deleteNode(struct Node **head, int value)` 用于删除链表中值为 `value` 的节点;3. 编写一个函数 `void reverseList(struct Node **head)` 用于反转链表。在 `main` 函数中进行测试,创建链表,插入一些节点,删除特定节点,然后反转链表并输出链表所有节点的值。
25.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构
struct Node {
    int data;
    struct Node *next;
};

// 在链表头部插入新节点
void insertNode(struct Node **head, int value) {
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = *head;
    *head = newNode;
}

// 删除链表中值为 value 的节点
void deleteNode(struct Node **head, int value) {
    struct Node *current = *head;
    struct Node *prev = NULL;

    while (current != NULL && current->data != value) {
        prev = current;
        current = current->next;
    }

    if (current == NULL) {
        return;
    }

    if (prev == NULL) {
        *head = current->next;
    } else {
        prev->next = current->next;
    }

    free(current);
}

// 反转链表
void reverseList(struct Node **head) {
    struct Node *prev = NULL;
    struct Node *current = *head;
    struct Node *next = NULL;

    while (current != NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }

    *head = prev;
}

// 打印链表所有节点的值
void printList(struct Node *head) {
    struct Node *current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

int main() {
    struct Node *head = NULL;

    insertNode(&head, 1);
    insertNode(&head, 2);
    insertNode(&head, 3);

    printf("Original list: ");
    printList(head);

    deleteNode(&head, 2);
    printf("List after deletion: ");
    printList(head);

    reverseList(&head);
    printf("List after reversal: ");
    printList(head);

    return 0;
}