MST

星途 面试题库

面试题:C语言指针访问结构体成员在链表中的应用

定义一个链表结构体struct Node { int data; struct Node *next; }; 编写一个函数void insertNode(struct Node **head, int value),在链表头部插入新节点,要求在函数中使用指针访问结构体成员,并处理好链表指针的指向关系。
20.1万 热度难度
编程语言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));
    if (newNode == NULL) {
        printf("内存分配失败\n");
        return;
    }
    newNode->data = value;
    newNode->next = *head;
    *head = newNode;
}