将列表转换为链接列表 [英] Converting a list to a linked list
问题描述
我试图找出将列表转换为链接列表的方法. 我已经有一个用于链接的类,但是我试图找出如何将列表转换为链接列表的方法,例如:
I'm trying to figure out to convert a list to a linked list. I already have a class for the link but I'm trying to figure out how to convert a list to linked list, for example:
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() +'>')
推荐答案
Matt的回答很好,但是超出了上面问题中描述的函数原型的约束.
Matt's answer is good, but it's outside the constraint of the function prototype described in the problem above.
阅读抽象/原型,看起来像是问题的创建者想用递归/动态编程方法来解决这个问题.这是一个相当标准的递归算法介绍.与其说是在Python中创建链接列表(不是真正有用或通用),不如说是更多地了解如何编写优雅的递归代码.
Reading the abstract/prototype, it looks like the creator of the problem wanted to solve this with recursive/dynamic programming methodology. This is a pretty standard recursive algorithm introduction. It's more about understanding how to write elegant recursive code more than creating linked-list in Python (not really useful or common).
这是我想出的一个解决方案.试试看:
Here's a solution I came up with. Try it out:
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.
"""
print('<' + helper(link).rstrip() +'>')
def list_to_link(lst):
"""Takes a Python list and returns a Link with the same elements.
"""
if len(lst) == 1:
return Link(lst[0])
return Link(lst[0], list_to_link(lst[1:])) # <<<< RECURSIVE
def helper(link):
if isinstance(link.first, Link):
first = '<' + helper(link.first).rstrip() + '>' # <<<< RECURSIVE
else:
first = str(link.first)
if link.rest != Link.empty:
return first + ' ' + helper(link.rest) # <<<< RECURSIVE
else:
return first + ' '
def main():
""" Below are taken from sample in function prototype comments
"""
link = list_to_link([1, 2, 3])
print_link(link)
link = Link(1, Link(2, Link(3)))
print_link(link)
link1 = Link(1, Link(Link(2), Link(3)))
print_link(link1)
link1 = Link(3, Link(Link(4), Link(5, Link(6))))
print_link(link1)
if __name__ == '__main__':
main()
这篇关于将列表转换为链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!