MST

星途 面试题库

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

实现一个简单的单向链表,链表节点结构体包含一个整数成员和一个指向下一个节点的结构体指针。编写函数完成链表的创建、节点插入(在头部插入)和遍历打印功能。结构体定义如下: ```c struct Node { int data; struct Node *next; }; ```
24.8万 热度难度
编程语言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));
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

// 创建链表
struct Node* createList(int values[], int size) {
    struct Node* head = NULL;
    for (int i = 0; i < size; i++) {
        struct Node* newNode = createNode(values[i]);
        newNode->next = head;
        head = newNode;
    }
    return head;
}

// 在头部插入节点
struct Node* insertAtHead(struct Node* head, int value) {
    struct Node* newNode = createNode(value);
    newNode->next = head;
    return newNode;
}

// 遍历并打印链表
void printList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

int main() {
    int values[] = {1, 2, 3, 4, 5};
    int size = sizeof(values) / sizeof(values[0]);

    struct Node* head = createList(values, size);
    printf("Original List: ");
    printList(head);

    head = insertAtHead(head, 0);
    printf("List after inserting 0 at head: ");
    printList(head);

    return 0;
}