头插法&尾插法

class Linked:

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

头插法

def head_create_linked(li: list) -> Linked:
    """
    头插法

    :param li: 输入列表
    :return: type(Linked)
    """
    head = Linked(li[0])

    for cur in li[1:]:
        node = Linked(cur)
        node.next = head
        head = node
    return head


def print_linked(linked):
    if linked:
        print(linked.item, end=",")
        print_linked(linked.next)



node = head_create_linked([1, 2, 3])
print_linked(node)

尾插法

def tail_create_linked(li: list) -> Linked:
    """
    尾插法

    :param li: 输入列表
    :return: type(Linked)
    """
    head = Linked(li[0])
    tail = head

    for cur in li[1:]:
        node = Linked(cur)
        tail.next = node
        tail = node

    return head

node = tail_create_linked([1, 2, 3])
print_linked(node)

results matching ""

    No results matching ""