gpt4 book ai didi

python - 将列表转换为链表

转载 作者:太空宇宙 更新时间:2023-11-04 03:29:44 24 4
gpt4 key购买 nike

我正在尝试将列表转换为链表。我已经有一个链接类,但我想弄清楚如何将列表转换为链表,例如:

def list_to_link(lst):
"""Takes a Python list and returns a Link with the same elements.

>>> link = list_to_link([1, 2, 3])
>>> print_link(link)
<1 2 3>
"""


class Link:

empty = ()

def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest

def print_link(link):
"""Print elements of a linked list link."""

>>> link = Link(1, Link(2, Link(3)))
>>> print_link(link)
<1 2 3>
>>> link1 = Link(1, Link(Link(2), Link(3)))
>>> print_link(link1)
<1 <2> 3>
>>> link1 = Link(3, Link(Link(4), Link(5, Link(6))))
>>> print_link(link1)
<3 <4> 5 6>
"""
print('<' +helper(link).rstrip() +'>')

最佳答案

我有一个使用虚拟 ListNode 的想法。这使代码简单整洁。

class ListNode:
def __init__(self, x):
self.val = x
self.next = None


def lst2link(lst):
cur = dummy = ListNode(0)
for e in lst:
cur.next = ListNode(e)
cur = cur.next
return dummy.next

关于python - 将列表转换为链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31553576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com