链表的创建&遍历打印

博客地址:https://www.cnblogs.com/zylyehuo/

# -*- coding: utf-8 -*-

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


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


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


def print_linklist(lk):
    while lk:
        print(lk.item, end=',')
        lk = lk.next


# linklist = create_linklist_head([1, 2, 3, 6, 8])
linklist = create_linklist_tail([1, 2, 3, 6, 8])
print_linklist(linklist)

posted @ 2023-08-17 15:51  zylyehuo  阅读(5)  评论(0编辑  收藏  举报