# 将列表转化为单链表
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def nums_to_linklist(li):
if not li: # 这里考虑到ACM模式下,假如输入数组为空就返回None
return None
else:
head = ListNode(li[0])
node = head
for i in li[1:]:
node.next = ListNode(i)
node = node.next
return head
if __name__ == '__main__':
li = [1, 3, 4, 5, 6]
num1 = nums_to_linklist(li) # 假如li为空列表的话,num1返回None
while num1:
print(num1.val, end=" ")
num1 = num1.next
结果
1 3 4 5 6