How to calculate the length of a doubly linked list in the C language?

To calculate the length of a doubly linked list, the following algorithm can be used:

  1. Declare a variable count and set it to 0 for counting purposes.
  2. Start from the head node of the linked list, and then traverse through each node of the linked list in order.
  3. Count increases by 1 each time a node is traversed.
  4. When reaching the last node of the linked list, the value of count is equal to the length of the linked list.
  5. Return the count as the length of the linked list.

Here is a sample code:

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

// 双向链表的节点结构
typedef struct Node {
    int data;
    struct Node *prev; // 前驱节点指针
    struct Node *next; // 后继节点指针
} Node;

// 计算双向链表的长度
int getLength(Node *head) {
    int count = 0;
    Node *current = head;
    while (current != NULL) {
        count++;
        current = current->next;
    }
    return count;
}

int main() {
    // 创建双向链表
    Node *head = (Node *)malloc(sizeof(Node));
    head->data = 1;
    head->prev = NULL;
    Node *node2 = (Node *)malloc(sizeof(Node));
    node2->data = 2;
    node2->prev = head;
    head->next = node2;
    Node *node3 = (Node *)malloc(sizeof(Node));
    node3->data = 3;
    node3->prev = node2;
    node2->next = node3;
    node3->next = NULL;

    // 计算链表的长度
    int length = getLength(head);
    printf("Length of the doubly linked list: %d\n", length);

    // 释放链表内存
    Node *current = head;
    while (current != NULL) {
        Node *temp = current;
        current = current->next;
        free(temp);
    }
    return 0;
}

In this code snippet, we first create a doubly linked list with 3 nodes. We then use the getLength() function to calculate the length of the list and print the result. Finally, we release the memory of the list.

Leave a Reply 0

Your email address will not be published. Required fields are marked *