输出单链表中的数据并统计单链表中的元素个数
时间: 2024-10-11 20:15:03 浏览: 74
在单链表中输出数据并统计元素个数,通常涉及遍历链表的操作。首先,你需要创建一个函数,例如`printList`来遍历链表,并打印出每个节点的数据。然后,你可以同时增加一个计数器来记录已访问的节点数量,当遍历结束后,这个计数器就是链表中的元素个数。
以下是一个简单的伪代码示例:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def print_list(head):
if head is not None:
current = head
while current is not None:
print(current.data)
current = current.next
print("总共有", len_nodes(head), "个元素")
def len_nodes(head):
count = 0
if head is not None:
current = head
while current is not None:
count += 1
current = current.next
return count
# 示例用法
head = Node(1) # 创建链表头结点
head.next = Node(2)
head.next.next = Node(3)
print_list(head) # 输出:1, 2, 3
```
在这个例子中,`print_list`函数会输出链表中的所有元素,而`len_nodes`函数则返回链表的长度,即元素个数。
阅读全文
相关推荐


















