递归,迭代 list序列化listnode 以及反序列化 python

算法刷题

递归,迭代 list序列化listnode 以及反序列化 python

年份
2023
分类
算法刷题

www.lanol.cn

递归法

def list2node(data):
    # 列表转节点
    if not data:
        return None
    return ListNode(data[0], list2node(data[1:]))


def node2list(head):
    # 节点转列表
    if not head:
        return []
    return [head.val] + node2list(head.next)

迭代法

# 迭代法
def list2node(data):
    # 列表转节点
    head = ListNode()
    p = head
    for i in data:
        p.next = ListNode(i)
        p = p.next
    return head.next


def node2list(head):
    # 节点转列表
    data = []
    while head:
        data.append(head.val)
        head = head.next
    return data