用c/c++编写代码统计链表的长度
时间: 2023-12-21 19:07:28 浏览: 39
下面是使用C语言编写统计链表长度的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode* next;
};
// 统计链表长度
int getLength(struct ListNode* head) {
int length = 0;
while (head != NULL) {
length++;
head = head->next;
}
return length;
}
int main() {
// 创建链表
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->val = 3;
head->next->next->next = NULL;
// 统计链表长度并输出
int length = getLength(head);
printf("链表长度为:%d\n", length);
// 释放链表节点内存
free(head->next->next);
free(head->next);
free(head);
return 0;
}
```
在示例代码中,我们定义了一个链表节点结构体,包含一个整型值val和一个指向下一个节点的指针next。然后定义了一个函数getLength来统计链表长度,该函数使用while循环遍历链表,每遍历一个节点就将长度加1。最后,我们在main函数中创建了一个包含三个节点的链表,调用getLength函数统计链表长度并输出,最后释放链表节点内存。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)