要计算双向链表的长度,可以使用以下算法:
下面是一个示例代码:
#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()
函数计算链表的长度,并将结果打印输出。最后释放了链表的内存。