将列表转换为链接列表

时间:2015-07-22 03:54:07

标签: python list linked-list

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

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() +'>')

3 个答案:

答案 0 :(得分:2)

马特的答案很好,但它超出了上述问题中描述的函数原型的约束。

阅读摘要/原型,看起来问题的创建者希望通过递归/动态编程方法来解决这个问题。这是一个非常标准的递归算法介绍。它更多的是理解如何编写优雅的递归代码而不是在Python中创建链表(不是真正有用或常见)。

这是我提出的解决方案。试试吧:

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()

答案 1 :(得分:0)

这就是你想要的。

class Node(object):
    def __init__(self, value, next=None):
        self.value = value
        self.reference = next

class LinkedList(object):
    def __init__(self, sequence):
        self.head = Node(sequence[0])
        current = self.head
        for item in sequence[1:]:
            current.reference = Node(item)
            current = current.reference
a = range(10)
li = LinkedList(li)
current = li.head
while current is not None:
    print current.value
    current = current.reference

答案 2 :(得分:0)

我有一个使用虚拟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