如何统计单链表中数据的个数python代码
时间: 2023-04-09 19:01:22 浏览: 99
可以使用以下代码来统计单链表中数据的个数:
```python
def count_nodes(head):
count = 0
current = head
while current is not None:
count += 1
current = current.next
return count
```
其中,`head` 是单链表的头节点,`current` 是当前节点,`current.next` 是下一个节点。通过遍历链表,每遍历一个节点就将计数器 `count` 加 1,最后返回计数器的值即可。
相关问题
如何统计单链表中数据的个数C语言函数代码
可以使用以下代码来统计单链表中数据的个数:
```
int count(struct Node* head) {
int count = 0;
struct Node* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
```
其中,`head` 是指向链表头节点的指针,`Node` 是链表节点的结构体,包含一个数据成员和一个指向下一个节点的指针。`count` 函数使用一个循环遍历链表,每遍历一个节点就将计数器加 1,直到遍历完整个链表。最后返回计数器的值,即链表中数据的个数。
统计单链表中元素e的个数全代码
ListNode *head; // 单链表头指针
int countElement(ListNode *head, int e) {
int count = 0;
ListNode *p = head; // 从头结点开始遍历
while (p != nullptr) {
if (p->val == e) { // 如果当前结点的值等于e
count++; // 计数器加1
}
p = p->next; // 继续遍历下一个结点
}
return count;
}