Skip to content

Problem 2.2: Python Lists (100pts)

Problem

In this problem, you will implement a convert function that converts a linked list Link into a Python list. That is, given a linked list, the function should return a standard Python list containing the same elements in the same order. For example, the linked list Link(1, Link(2, Link(3))) should be converted to the Python list [1, 2, 3].

Note that the linked list could be nested, meaning that some elements of the linked list could themselves be another linked list. For example, the linked list Link(1, Link(Link(2, Link(3)), Link(4))) should be converted to the Python list [1, [2, 3], 4].

You can assume that the input linked list have no cycles (i.e., it will always terminate with Link.empty), such that it can be converted to a Python list without infinite recursion.

在本问题中,你将实现一个 convert 函数,它将一个链表 Link 转换为一个 Python 列表。 也就是说,给定一个链表,该函数应返回一个包含相同元素且顺序相同的标准 Python 列表。 例如,链表 Link(1, Link(2, Link(3))) 应该被转换为 Python 列表 [1, 2, 3]

请注意,该链表可能是嵌套的,这意味着链表中的某些元素本身也可能是另一个链表。 例如,链表 Link(1, Link(Link(2, Link(3)), Link(4))) 应该被转换为 Python 列表 [1, [2, 3], 4]

你可以假设输入的链表没有循环(即它总是以 Link.empty 终止),因此它可以被转换为一个 Python 列表而不会发生无限递归。

def convert(link):
    """Convert a linked list to a Python list.

    >>> l = Link(Link(Link(1, Link(Link(2, Link(3)), Link(4))), Link(5)))
    >>> print(l)
    <<<1 <2 3> 4> 5>>
    >>> convert(l)
    [[[1, [2, 3], 4], 5]]
    >>> type(convert(l)) is list
    True
    """
    "*** YOUR CODE HERE ***"

Hints

Hint:

You may find it useful to check whether an element is an instance of the Link class using the isinstance function. For example, isinstance(x, Link) returns True if x is a Link object, and False otherwise. However, be careful handling the empty linked list Link.empty, which actually may not be an instance of Link.

  • 你可能会发现使用 isinstance 函数来检查一个元素是否是 Link 类的实例很有用。 例如,如果 \(x\) 是一个 Link 对象,isinstance(x, Link) 将返回 True,否则返回 False。 但是,请小心处理空链表 Link.empty,它实际上可能不是 Link 的一个实例。