温馨提示×

c语言双向链表是如何实现的

小樊
82
2024-07-08 19:33:27
栏目: 编程语言

在C语言中,双向链表可以通过结构体和指针来实现。一个典型的双向链表节点结构体可以定义如下:

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

在双向链表中,每个节点包含一个数据域和两个指针域,分别指向前一个节点和后一个节点。接下来可以定义一个双向链表结构体来保存链表的头节点和尾节点:

typedef struct {
    Node* head;
    Node* tail;
} DoublyLinkedList;

实现双向链表的基本操作,包括初始化、插入节点、删除节点等操作。以下是一个简单的双向链表的实现示例:

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

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

typedef struct {
    Node* head;
    Node* tail;
} DoublyLinkedList;

DoublyLinkedList* createDoublyLinkedList() {
    DoublyLinkedList* list = (DoublyLinkedList*)malloc(sizeof(DoublyLinkedList));
    list->head = NULL;
    list->tail = NULL;
    return list;
}

void insertNode(DoublyLinkedList* 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 {
        list->tail->next = newNode;
        newNode->prev = list->tail;
        list->tail = newNode;
    }
}

void deleteNode(DoublyLinkedList* list, int data) {
    Node* current = list->head;
    while (current != NULL) {
        if (current->data == data) {
            if (current == list->head) {
                list->head = current->next;
                if (list->head != NULL) {
                    list->head->prev = NULL;
                }
            } else if (current == list->tail) {
                list->tail = current->prev;
                list->tail->next = NULL;
            } else {
                current->prev->next = current->next;
                current->next->prev = current->prev;
            }

            free(current);
            return;
        }

        current = current->next;
    }
}

void printList(DoublyLinkedList* list) {
    Node* current = list->head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    DoublyLinkedList* list = createDoublyLinkedList();

    insertNode(list, 1);
    insertNode(list, 2);
    insertNode(list, 3);

    printList(list);

    deleteNode(list, 2);

    printList(list);

    return 0;
}

在上面的示例中,首先定义了Node和DoublyLinkedList结构体来表示双向链表的节点和链表。然后实现了创建双向链表、插入节点、删除节点和打印链表的操作函数。在main函数中,创建一个双向链表并对其进行操作,最后打印出链表的内容。

0