统计单链表中元素e的个数全代码
时间: 2023-05-27 12:05:05 浏览: 49
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;
}
相关问题
统计单链表中元素e的个数
算法思路:
遍历单链表,遇到一个值为e的节点就将计数器加1,最终返回计数器的值。
算法实现:
```python
def count_element(head, e):
count = 0
p = head
while p:
if p.val == e:
count += 1
p = p.next
return count
```
其中,head为链表的头节点,e为要统计的元素值。节点的值可以根据具体情况进行修改。
如何统计单链表中数据的个数python代码
可以使用以下代码来统计单链表中数据的个数:
```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,最后返回计数器的值即可。