C言語 リスト構造の作り方と実装【初心者向け】

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()関数を使って新しいノードを作成し、ポインタを使ってそれらをリンクさせてリストを構築する。最後に、リストを走査して各ノードの値を出力する。

bannerAds