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

Lan
Lan
2023-01-12 / 0 评论 / 58 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年01月12日,已超过469天没有更新,若内容或图片失效,请留言反馈。

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
0

评论 (0)

取消