递归法
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)