MST

星途 面试题库

面试题:C语言复杂数据结构中NULL指针的安全检查策略

假设有一个链表结构`struct Node { int data; struct Node *next; };`,编写一个函数`void traverseList(struct Node *head)`,在遍历链表的过程中对每一个节点指针(包括`head`指针以及`next`指针)进行NULL指针安全检查,确保遍历过程不会因为NULL指针而崩溃,并且在遇到NULL指针时记录下出现的位置并输出相关提示信息。
48.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

struct Node {
    int data;
    struct Node *next;
};

void traverseList(struct Node *head) {
    struct Node *current = head;
    int position = 0;

    while (current != NULL) {
        if (current == NULL) {
            printf("NULL pointer detected at position %d (head pointer).\n", position);
            return;
        }
        printf("Data at position %d: %d\n", position, current->data);
        if (current->next == NULL) {
            printf("NULL pointer detected at position %d (next pointer).\n", position + 1);
        }
        current = current->next;
        position++;
    }
}