如何输出单链表中的元素
- 科技动态
- 2025-02-10 19:01:21
- 6
.png)
输出单链表中的元素可以通过遍历链表中的每个节点,并打印出节点的值来实现。以下是一个使用Python实现的简单示例:定义一个单链表的节点类和单链表类:```pythonc...
输出单链表中的元素可以通过遍历链表中的每个节点,并打印出节点的值来实现。以下是一个使用Python实现的简单示例:
.png)
定义一个单链表的节点类和单链表类:
```python
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if not self.head:
self.head = ListNode(value)
else:
current = self.head
while current.next:
current = current.next
current.next = ListNode(value)
def print_list(self):
current = self.head
while current:
print(current.value, end=' ')
current = current.next
print() 打印换行符,结束输出
```
然后,创建一个链表并添加一些元素,然后调用`print_list`方法输出链表中的元素:
```python
创建链表
linked_list = LinkedList()
添加元素
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.append(4)
输出链表中的元素
linked_list.print_list()
```
执行上述代码,输出结果应该是:
```
1 2 3 4
```
这个示例中,`LinkedList`类有一个`append`方法用于向链表末尾添加新元素,`print_list`方法用于输出链表中的所有元素。
本文链接:http://www.hoaufx.com/ke/484927.html