MST

星途 面试题库

面试题:C语言匿名结构体在复杂数据结构中的深度应用

设计一个链表结构,其中链表节点使用匿名结构体来定义。该链表节点需要包含一个整型数据成员`data`以及一个指向下一个节点的指针成员。实现链表的创建、插入节点(在指定位置插入)和删除节点(删除指定值的节点)的功能。要求代码完整且逻辑清晰,考虑边界情况。
26.5万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#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用于释放链表占用的内存。