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

 

posted @ 2018-10-24 19:26  chen狗蛋儿  阅读(1660)  评论(0编辑  收藏  举报