C言語でlist構造体を作る方法と使い方を詳しく解説

目次から探す

list構造体の利用例

list構造体は、データの管理やアルゴリズムの実装に非常に便利です。

ここでは、list構造体を使った具体的な利用例を紹介します。

list構造体を使ったデータの管理

例えば、学生のデータを管理するプログラムを考えてみましょう。

各学生の名前と年齢を管理するために、list構造体を使用します。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 学生のデータを表す構造体
typedef struct Student {
    char name[50];
    int age;
    struct Student* next;
} Student;
// 学生のデータを追加する関数
void addStudent(Student** head, char* name, int age) {
    // 新しい学生のデータを作成
    Student* newStudent = (Student*)malloc(sizeof(Student));
    strcpy(newStudent->name, name);
    newStudent->age = age;
    newStudent->next = NULL;
    // リストの先頭に追加
    if (*head == NULL) {
        *head = newStudent;
    } else {
        newStudent->next = *head;
        *head = newStudent;
    }
}
// 学生のデータを表示する関数
void printStudents(Student* head) {
    Student* current = head;
    while (current != NULL) {
        printf("Name: %s, Age: %d\n", current->name, current->age);
        current = current->next;
    }
}
int main() {
    Student* head = NULL;
    // 学生のデータを追加
    addStudent(&head, "学生A", 20);
    addStudent(&head, "学生B", 18);
    addStudent(&head, "学生C", 22);
    // 学生のデータを表示
    printStudents(head);
    return 0;
}

上記のプログラムでは、Studentという構造体を定義し、addStudent関数で新しい学生のデータを追加しています。

printStudents関数では、リスト内の学生のデータを表示しています。

実行結果は以下のようになります。

Name: 学生C, Age: 22
Name: 学生B, Age: 18
Name: 学生A, Age: 20

このように、list構造体を使うことで、複数のデータを管理することができます。

list構造体を使ったアルゴリズムの実装

list構造体は、データの追加や削除、検索などのアルゴリズムの実装にも役立ちます。

例えば、リスト内の特定の要素を検索する関数を実装してみましょう。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 学生のデータを表す構造体
typedef struct Student {
    char name[50];
    int age;
    struct Student* next;
} Student;
// 学生のデータを追加する関数
void addStudent(Student** head, char* name, int age) {
    // 新しい学生のデータを作成
    Student* newStudent = (Student*)malloc(sizeof(Student));
    strcpy(newStudent->name, name);
    newStudent->age = age;
    newStudent->next = NULL;
    // リストの先頭に追加
    if (*head == NULL) {
        *head = newStudent;
    } else {
        newStudent->next = *head;
        *head = newStudent;
    }
}
// 学生のデータを検索する関数
Student* findStudent(Student* head, char* name) {
    Student* current = head;
    while (current != NULL) {
        if (strcmp(current->name, name) == 0) {
            return current;
        }
        current = current->next;
    }
    return NULL;
}
int main() {
    Student* head = NULL;
    // 学生のデータを追加
    addStudent(&head, "学生A", 20);
    addStudent(&head, "学生B", 18);
    addStudent(&head, "学生C", 22);
    // 学生のデータを検索
    Student* foundStudent = findStudent(head, "学生B");
    if (foundStudent != NULL) {
        printf("Name: %s, Age: %d\n", foundStudent->name, foundStudent->age);
    } else {
        printf("学生が見つかりませんでした。\n");
    }
    return 0;
}

上記のプログラムでは、findStudent関数を実装しています。

この関数は、指定した名前の学生をリスト内で検索し、見つかった場合はその学生のデータを返します。

実行結果は以下のようになります。

Name: 学生B, Age: 18

このように、list構造体を使うことで、様々なアルゴリズムを実装することができます。

1 2 3 4

目次から探す