c語(yǔ)言雙向鏈表實(shí)現(xiàn)的方法是什么

小億
86
2023-12-27 15:24:26

要實(shí)現(xiàn)一個(gè)雙向鏈表的數(shù)據(jù)結(jié)構(gòu),你可以按照以下步驟進(jìn)行:

  1. 定義一個(gè)節(jié)點(diǎn)結(jié)構(gòu)體。每個(gè)節(jié)點(diǎn)應(yīng)該包含兩個(gè)指針,一個(gè)指向前一個(gè)節(jié)點(diǎn),一個(gè)指向后一個(gè)節(jié)點(diǎn)。同時(shí),節(jié)點(diǎn)還應(yīng)該包含存儲(chǔ)數(shù)據(jù)的變量。
typedef struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
} Node;
  1. 定義鏈表結(jié)構(gòu)體。鏈表結(jié)構(gòu)體應(yīng)該包含頭節(jié)點(diǎn)和尾節(jié)點(diǎn)的指針。
typedef struct LinkedList {
    Node* head;
    Node* tail;
} LinkedList;
  1. 實(shí)現(xiàn)初始化函數(shù)。初始化函數(shù)用于創(chuàng)建一個(gè)空鏈表。
void initLinkedList(LinkedList* list) {
    list->head = NULL;
    list->tail = NULL;
}
  1. 實(shí)現(xiàn)插入節(jié)點(diǎn)的函數(shù)。插入函數(shù)需要考慮頭節(jié)點(diǎn)和尾節(jié)點(diǎn)的情況。
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;
    }
}
  1. 實(shí)現(xiàn)刪除節(jié)點(diǎn)的函數(shù)。刪除函數(shù)需要考慮節(jié)點(diǎn)在鏈表中的位置。
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;
    }
}
  1. 實(shí)現(xiàn)打印鏈表的函數(shù)。
void printLinkedList(LinkedList* list) {
    Node* current = list->head;

    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    printf("\n");
}

完成了上述步驟后,你就可以使用這些函數(shù)來(lái)創(chuàng)建和操作雙向鏈表了。

0