MST

星途 面试题库

面试题:C语言结构体指针空指针判断与动态内存

定义一个结构体struct Node { int data; struct Node *next; }; 编写一个函数用于创建新节点并返回新节点的指针。在另一个函数中,从链表头开始遍历链表,在遍历过程中,每次获取下一个节点指针时,要进行空指针判断。如果遇到空指针,打印'到达链表末尾',如果链表遍历完成,打印'链表遍历结束'。假设链表头指针可以为NULL。
44.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义结构体
struct Node {
    int data;
    struct Node *next;
};

// 创建新节点的函数
struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        return NULL;
    }
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

// 遍历链表的函数
void traverseList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        if (current->next == NULL) {
            printf("到达链表末尾\n");
        }
        current = current->next;
    }
    printf("链表遍历结束\n");
}

你可以使用以下方式调用这些函数:

int main() {
    // 创建链表
    struct Node* head = createNode(1);
    struct Node* node2 = createNode(2);
    struct Node* node3 = createNode(3);

    head->next = node2;
    node2->next = node3;

    // 遍历链表
    traverseList(head);

    // 释放链表内存(这里省略具体释放代码)
    return 0;
}