数据结构统计带头结点的单链表中结点的个数,并依次输出链表中元素的值
时间: 2024-09-08 09:02:44 浏览: 60
在数据结构中,如果你想要统计带头结点的单链表中节点的数量,你可以遍历整个链表。首先,需要一个指针指向头结点,然后每次迭代将指针移动到下一个节点,直到指针变为NULL,这表示已经到达了链表的末尾。在这个过程中计数器会递增1。
Python示例代码如下:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def count_and_output(head):
if head is None:
return 0
count = 1
current = head.next
while current:
print(current.val)
count += 1
current = current.next
return count
# 使用示例
head = ListNode(1) # 假设有一个简单的链表: 1 -> None
head.next = ListNode(2) # 另一个节点: 2 -> None
print(count_and_output(head)) # 输出: 2 (节点个数), 先输出1再输出2
```
在这个函数中,`count_and_output`接收链表头结点作为参数,它先检查头结点是否为空,然后开始遍历,同时打印节点值并更新计数器。当链表遍历完,返回的就是节点总数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)