温馨提示×

c语言双向链表的长度如何计算

小亿
88
2023-12-27 15:36:28
栏目: 编程语言

要计算双向链表的长度,可以使用以下算法:

  1. 定义一个变量count并初始化为0,用于计数。
  2. 从链表的头节点开始,依次遍历链表的每个节点。
  3. 每次遍历一个节点,count加1。
  4. 当遍历到链表的最后一个节点时,count的值即为链表的长度。
  5. 返回count作为链表的长度。

下面是一个示例代码:

#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;
}

这段代码中,我们首先创建了一个包含3个节点的双向链表。然后使用getLength()函数计算链表的长度,并将结果打印输出。最后释放了链表的内存。

0