链表的插入和遍历

2019-08-22  本文已影响0人  ___大鱼___
链表1.png 创建链表.png
# 链表

class Node:
    def __init__(self, item):
        self.item = item
        self.next = None

    def __str__(self):
        return str(self.item)


# 头插法
def create_linklist_head(li):
    head = Node(li[0])
    for ele in li[1:]:
        node = Node(ele)
        node.next = head
        head = node
    return head


# 尾插法
def create_linklist_tail(li):
    head = Node(li[0])
    tail = head
    for ele in li[1:]:
        node = Node(ele)
        tail.next = node
        tail = node
    return head


# 遍历链表
def print_linklist(head):
    while head:
        print(head.item)
        head = head.next


if __name__ == '__main__':

    node_head = create_linklist_tail([x for x in range(100)])
    print_linklist(node_head)  # 正序打印
    node_head = create_linklist_head([x for x in range(100)])
    print_linklist(node_head)  # 倒叙打印
上一篇 下一篇

猜你喜欢

热点阅读