MST

星途 面试题库

面试题:C语言指针变量初始化高级难度题

在C语言中,假设有一个结构体如下: ```c struct Node { int data; struct Node *next; }; ``` 请编写一段代码,初始化一个`struct Node`类型的指针`head`,并创建一个包含三个节点的链表,节点的数据分别为1、2、3,同时要正确初始化每个节点的`next`指针。
21.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

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

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

    // 创建第一个节点
    newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = 1;
    newNode->next = NULL;
    head = newNode;
    current = head;

    // 创建第二个节点
    newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = 2;
    newNode->next = NULL;
    current->next = newNode;
    current = current->next;

    // 创建第三个节点
    newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = 3;
    newNode->next = NULL;
    current->next = newNode;

    // 打印链表数据验证
    current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");

    // 释放链表内存
    current = head;
    struct Node *temp = NULL;
    while (current != NULL) {
        temp = current;
        current = current->next;
        free(temp);
    }

    return 0;
}