链表,如果uu init_uu2;()中param中的元素是iterable,则从i构造新的链表

2024-04-29 13:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个链表的实现

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

class Linked_list:
    def __init__(self, llist=None):
        self.head = None
        self.tail = None
        if llist is not None:
            for i in llist:
                self.append(i)

    def add_head(self, data):
        self.head = Node(data, self.head)
        if self.tail is None:
            self.tail = self.head

    def append(self, data):
        if self.head is None:
            self.add_head(data)
        else:
            self.tail.next = Node(data)
            self.tail = self.tail.next

我想更改__init__(),因此如果llist参数包含iterable元素(list、range()、string、tuple等),它将从中构造一个新的链接列表。我相信递归是可行的,但是我真的很困惑如何在__init__()中实现它。例如

a = Linked_list([1, 2, Linked_list(range(5)), Linked_list(range(3))])
b = Linked_list([1, 2, list(range(5)), list(range(3))])
c = Linked_list([1, 2,  (0, 1, 2, 3, 4), (0, 1, 2)])

a、b、c应返回相同的链接列表


Tags: selfnonenodedataifinitisdef
2条回答

您可以使用isinstance()来检查llist中值的类型,并相应地执行操作。递归基本上是免费的,通过构造函数实现的。你知道吗

from collections import Iterable   # Using Python 2.7

class Linked_list:

    def __init__(self, llist=None):

        ...      # Same as your code.

        if llist is not None:
            for i in llist:
                if isinstance(i, basestring):
                    ll = Linked_list()
                    for c in i:
                        ll.append(c)
                    self.append(ll)
                elif isinstance(i, Iterable):
                    self.append(Linked_list(i))
                else:
                    self.append(i)

    ...

    def __repr__(self):
        xs = []
        nd = self.head
        while nd is not None:
            xs.append(nd.data)
            nd = nd.next
        return repr(xs)

a = Linked_list([1, 2, Linked_list(range(5)), Linked_list(range(3))])
b = Linked_list([1, 2, list(range(5)), list(range(3))])
c = Linked_list([1, 2,  (0, 1, 2, 3, 4), (0, 1, 2)])
d = Linked_list([1, 2,  (0, 1, range(4), 3, 4), (0, 1, [4,5,'abc'])])

print a
print b
print c
print d

输出:

[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, [0, 1, 2, 3], 3, 4], [0, 1, [4, 5, ['a', 'b', 'c']]]]

要测试某个内容是否可iterable,可以使用collection.abc模块中的abstract base class

isinstance(llist, collection.abc.Iterable)

请注意,Python为iterable objects定义了一个行为/协议,这可能不是您练习的目的,但是您可能会对遵守它感兴趣。你知道吗

相关问题 更多 >