如何将数组加入链表里
- 编程技术
- 2025-02-02 10:42:12
- 1
要将数组元素加入到链表中,首先需要定义链表的数据结构,然后创建一个链表节点类,并编写函数来添加节点。以下是一个简单的示例,演示如何将数组元素添加到一个单向链表中。```...
要将数组元素加入到链表中,首先需要定义链表的数据结构,然后创建一个链表节点类,并编写函数来添加节点。以下是一个简单的示例,演示如何将数组元素添加到一个单向链表中。
```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 from_array(self, array):
for element in array:
self.append(element)
使用LinkedList类
array = [1, 2, 3, 4, 5]
linked_list = LinkedList()
linked_list.from_array(array)
输出链表元素以验证
current = linked_list.head
while current:
print(current.value, end=' ')
current = current.next
```
这段代码定义了一个`ListNode`类,用于创建链表节点,以及一个`LinkedList`类,其中包含一个`append`方法用于向链表末尾添加元素,以及一个`from_array`方法,它接受一个数组作为参数,并将数组的每个元素添加到链表中。
在`from_array`方法中,我们遍历数组中的每个元素,并使用`append`方法将其添加到链表中。我们创建了一个`LinkedList`实例,并使用`from_array`方法将数组元素添加到链表中,然后打印链表的内容以验证结果。
本文链接:http://www.xinin56.com/bian/429701.html
上一篇:深字音序是什么