请为我写一段计算双向链表长度的c语言代码
时间: 2024-03-24 12:39:36 浏览: 12
以下是一个简单的计算双向链表长度的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// 计算双向链表长度
int countNodes(struct Node* head) {
int count = 0;
struct Node* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
int main() {
// 创建双向链表
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->prev = NULL;
head->next = second;
second->data = 2;
second->prev = head;
second->next = third;
third->data = 3;
third->prev = second;
third->next = NULL;
// 计算双向链表长度并打印结果
int length = countNodes(head);
printf("双向链表的长度为: %d\n", length);
// 释放内存
free(head);
free(second);
free(third);
return 0;
}
```
上述代码中,我们创建了一个双向链表,并定义了一个计算链表长度的函数`countNodes()`。函数中使用一个计数器`count`遍历整个链表,并在遍历每个节点时将计数器加1。最终返回计数器的值即为链表的长度。在主函数中,我们调用了`countNodes()`函数来计算链表长度,并打印结果。最后,我们释放了双向链表中的所有节点的内存。