Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Created March 2, 2026 06:59
Show Gist options
  • Select an option

  • Save kujirahand/917859581ffecca795610bb5be14b2ce to your computer and use it in GitHub Desktop.

Select an option

Save kujirahand/917859581ffecca795610bb5be14b2ce to your computer and use it in GitHub Desktop.
単方向リスト
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 単方向リストのノード構造体 --- (*1)
typedef struct Node {
char *value;
struct Node *next;
} Node;
// 文字列をコピーする関数 --- (*2)
char *clone_str(const char *src) {
size_t len = strlen(src) + 1;
char *dest = (char *)malloc(len);
if (dest == NULL) {
fprintf(stderr, "メモリ確保に失敗しました。\n");
exit(EXIT_FAILURE);
}
memcpy(dest, src, len);
return dest;
}
// ノードを作成する関数 --- (*3)
Node *create_node(const char *value) {
Node *node = (Node *)malloc(sizeof(Node));
if (node == NULL) {
fprintf(stderr, "メモリ確保に失敗しました。\n");
exit(EXIT_FAILURE);
}
node->value = clone_str(value);
node->next = NULL;
return node;
}
// リストの末尾に文字列を追加する関数 --- (*4)
void push_data(Node **head, const char *value) {
Node *node = create_node(value);
if (*head == NULL) {
*head = node;
return;
}
// リストの末尾のノードを探す
Node *current = *head;
while (current->next != NULL) {
current = current->next;
}
// リストにノードをつなげる
current->next = node;
}
// リストの一覧を表示する関数 --- (*5)
void print_list(const Node *head) {
const Node *current = head;
while (current != NULL) {
printf("- %s\n", current->value);
current = current->next;
}
}
// リストのメモリを解放する関数 --- (*6)
void free_list(Node **head) {
Node *current = *head;
while (current != NULL) {
Node *next = current->next;
free(current->value);
free(current);
current = next;
}
*head = NULL;
}
// メイン関数 --- (*7)
int main(void) {
Node *head = NULL;
// データの追加
push_data(&head, "りんご");
push_data(&head, "みかん");
push_data(&head, "バナナ");
// リストの一覧を表示
print_list(head);
// メモリの解放
free_list(&head);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment