Python: 如何将LinkedList转换为列表 (List)
可以使用Python内置的list()函数将LinkedList转换为列表。
例如,假设我们有以下LinkedList:
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node2.next = node3
head = node1
我们可以使用list()函数将其转换为列表:
lst = list()
curr = head
while curr:
lst.append(curr.val)
curr = curr.next
print(lst) # output: [1, 2, 3]
或者更简洁的方法是使用列表推导式:
lst = [node.val for node in head]
print(lst) # output: [1, 2, 3]
原文地址: https://www.cveoy.top/t/topic/nuYa 著作权归作者所有。请勿转载和采集!