温馨提示×

c语言怎么创建一个链表

小亿
93
2024-02-23 10:04:28
栏目: 编程语言

在C语言中,可以通过定义结构体来创建链表。以下是一个简单的例子:

#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct Node {
    int data;
    struct Node* next;
};

// 创建新节点
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if(newNode == NULL) {
        printf("Memory allocation failed\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

int main() {
    // 创建链表头指针
    struct Node* head = NULL;

    // 添加节点到链表
    struct Node* newNode = createNode(10);
    head = newNode;

    newNode->next = createNode(20);
    newNode = newNode->next;

    newNode->next = createNode(30);
    newNode = newNode->next;

    // 遍历链表并打印节点的值
    struct Node* current = head;
    while(current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    return 0;
}

在上面的代码中,首先定义了一个Node结构体来表示链表节点。然后通过createNode()函数创建新的节点,并通过指针将它们连接在一起形成链表。最后通过遍历链表打印每个节点的值。

0