Python实现单链表
定义链表结构:
1 class ListNode: 2 def __init__(self, x): 3 self.val = x 4 self.next = None
输出该链表l1的元素:
while l1: print(l1.val) l1 = l1.next
将一个list的数据存为链表:
def list2listnode(num): head = ListNode(num[0]) result = head for i in range(1,len(num)): head.next = ListNode(num[i]) head = head.next return result