C\C++统计链表的长度
时间: 2023-09-07 14:11:55 浏览: 122
要统计链表的长度,可以遍历整个链表,每经过一个节点就计数器加1,直到遍历完整个链表。
以下是一个示例代码:
```python
def get_length(head):
"""
统计链表的长度
:param head: 链表头节点
:return: 链表的长度
"""
length = 0
cur = head
while cur:
length += 1
cur = cur.next
return length
```
其中,`head` 表示链表的头节点,`cur` 表示当前节点。在循环中,每经过一个节点,计数器 `length` 就加1,直到 `cur` 为 `None`,即遍历完整个链表。最后返回计数器 `length` 即可得到链表的长度。
相关问题
C/C++统计链表的长度
以下是一个基本的C语言程序,用于计算链表的长度:
```
#include <stdio.h>
// 链表节点定义
struct Node {
int data;
struct Node *next;
};
// 计算链表长度
int length(struct Node *head) {
int len = 0;
while (head != NULL) {
len++;
head = head->next;
}
return len;
}
int main() {
// 创建链表
struct Node *head = NULL;
struct Node *second = NULL;
struct Node *third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// 计算链表长度
int len = length(head);
printf("链表长度为:%d\n", len);
// 释放内存
free(head);
free(second);
free(third);
return 0;
}
```
c++中链表长度怎么求
在C++中求链表的长度可以通过遍历链表的方式来实现。你可以定义一个变量来计数链表中节点的数量,然后在遍历链表时,每遇到一个节点就将计数器加一。下面是一个示例代码:
```cpp
#include <iostream>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
int getListLength(ListNode* head) {
int length = 0;
ListNode* current = head;
while (current != nullptr) {
length++;
current = current->next;
}
return length;
}
int main() {
// 创建链表
ListNode* head = new ListNode(1);
ListNode* node1 = new ListNode(2);
ListNode* node2 = new ListNode(3);
head->next = node1;
node1->next = node2;
// 求链表长度
int length = getListLength(head);
std::cout << "链表长度为:" << length << std::endl;
// 释放链表内存
delete node2;
delete node1;
delete head;
return 0;
}
```
在上面的示例代码中,我们定义了一个 `getListLength` 函数来计算链表的长度。通过不断更新 `current` 指针,直到指向最后一个节点的 `next` 为 `nullptr`,就可以统计出链表中节点的数量。最后在 `main` 函数中,我们创建了一个包含3个节点的链表,并输出了链表的长度为3。