C言語で簡単な単方向リストをどのように記述しますか?
以下は単純な単方向リストのC言語実装です。
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
// 创建链表节点
struct ListNode* createNode(int value) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = value;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表尾部
void insert(struct ListNode** head, int value) {
struct ListNode* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
struct ListNode* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 删除指定值的节点
void removeNode(struct ListNode** head, int value) {
struct ListNode* cur = *head;
struct ListNode* prev = NULL;
while (cur != NULL) {
if (cur->val == value) {
if (prev == NULL) { // 删除头节点
*head = cur->next;
} else {
prev->next = cur->next;
}
free(cur);
return;
}
prev = cur;
cur = cur->next;
}
}
// 打印链表
void printList(struct ListNode* head) {
struct ListNode* cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
struct ListNode* head = NULL;
// 插入节点
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
// 打印链表
printList(head);
// 删除节点
removeNode(&head, 2);
// 打印链表
printList(head);
return 0;
}
このコードは、シンプルな単方向リストを実装しており、ノードの作成、挿入、削除、およびリストの印刷機能が含まれています。main()関数では、これらの機能をどのように使用するかが示されています。