C言語で双方向連結リストを作成の方法

双方向リンクリストを作成するには、前へのポインタ、次へのポインタ、データを含む構造体を準備します。その後、次の手順で作成していきます。

  1. struct Node{
    int data;
    struct Node *prev;
    struct Node *next;
    };
  2. struct Node* head = 0;
    struct Node* tail = 0;
  3. struct Node* newNode = malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->prev = NULL;
    newNode->next = NULL;
  4. if (head == NULL) {head = newNode;tail = newNode;}
  5. else {
    tail->next = newNode;
    newNode->prev = tail;
    tail = newNode;
    }
  6. 3-5のステップをすべてのノードの追加が完了するまで繰り返します。

完全なサンプルコードを次に示します。

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
};

void insert(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->prev = NULL;
    newNode->next = NULL;
    
    if (head == NULL) {
        head = newNode;
        tail = newNode;
    }
    else {
        tail->next = newNode;
        newNode->prev = tail;
        tail = newNode;
    }
}

void display() {
    struct Node* current = head;
    if (head == NULL) {
        printf("List is empty.\n");
        return;
    }
    printf("Nodes in the doubly linked list: \n");
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    head = NULL;
    tail = NULL;
    
    insert(1);
    insert(2);
    insert(3);
    
    display();
    
    return 0;
}

двусвязанный список созданный в коде ниже состоит из 3 элементов (1, 2, 3) , а его вывод: Nodes in the doubly linked list: 1 2 3

bannerAds