C言語で双方向リストを実装する方法は何ですか?
双方向リストのデータ構造を実装するには、以下の手順に従うことができます。
- ノード構造体を定義します。各ノードには、前のノードを指すポインタと次のノードを指すポインタが含まれるべきです。同時に、ノードにはデータを保存する変数も含まれるべきです。
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
- リンクリスト構造体を定義してください。そのリンクリスト構造体には、ヘッドノードとテイルノードを指すポインタが含まれている必要があります。
typedef struct LinkedList {
Node* head;
Node* tail;
} LinkedList;
- 初期化関数を実装します。初期化関数は空のリストを作成するために使用されます。
void initLinkedList(LinkedList* list) {
list->head = NULL;
list->tail = NULL;
}
- ノードを挿入する関数を実装する。挿入関数は、ヘッドノードとテールノードの場合を考慮する必要がある。
void insertNode(LinkedList* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
list->tail = newNode;
} else {
newNode->prev = list->tail;
list->tail->next = newNode;
list->tail = newNode;
}
}
- ノードを削除する機能を実装する。削除機能では、ノードの位置を考慮する必要があります。
void deleteNode(LinkedList* list, int data) {
Node* current = list->head;
while (current != NULL) {
if (current->data == data) {
if (current->prev != NULL) {
current->prev->next = current->next;
} else {
list->head = current->next;
}
if (current->next != NULL) {
current->next->prev = current->prev;
} else {
list->tail = current->prev;
}
free(current);
return;
}
current = current->next;
}
}
- リストをプリントする関数を実装する。
void printLinkedList(LinkedList* list) {
Node* current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
上記の手順を完了すると、これらの関数を使用して双方向リストを作成および操作することができます。