C言語でリンクリストにノードを追加する方法は何ですか。
C言語では、リストにノードを追加する方法は、次の手順で行われます。
- ノードを表す構造体を定義し、その構造体にはデータメンバと次のノードを指すポインタメンバが含まれています。例えば:
struct Node {
int data;
struct Node* next;
};
- 新しいノードを作成し、そのノードにメモリを割り当てます。例えば:
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
- 新しいノードのデータ値を設定します。例:
newNode->data = 10;
- 新しいノードのnextポインタをリストの先頭ノードに向ける。例えば:
newNode->next = head;
- 新しいノードをリストの新しい先頭ノードとして設定します。例えば:
head = newNode;
完璧なサンプルコードは以下の通りです:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
insert(&head, 10);
insert(&head, 20);
insert(&head, 30);
printList(head);
return 0;
}
このコードは、値が10、20、30のノードを含むリストを作成し、リストの内容を出力します:30 20 10。