python - 链表,如果 __init__() 中参数中的元素是可迭代的,则从中构造新的链表

标签 python python-3.x recursion linked-list initialization

我有这个链表的实现,

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 参数包含一个可迭代元素(list、range()、string、tuple 等)它将从中构建一个新的 Linked_list。我相信递归是可行的方法,但我真的很困惑如何在 __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 应该返回相同的 Linked_list

最佳答案

您可以使用 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']]]]

关于python - 链表,如果 __init__() 中参数中的元素是可迭代的,则从中构造新的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29301966/

相关文章:

python - 如果条件为 true,则使用前 x 行的相反值填充行

python - 由于未知原因,文本显示质量低下

python - 如何将字符串转换为日期时间?

python - pandas groupby 使用一列列表值

c++ - 是否可以修复可变参数模板函数的参数?

python - 在python中使用BeautifulSoup提取id以特定字符串开头的元素

python - SQLite WAL 模式,后台线程检查点,wal-journal 永不收缩

python-3.x - 使用 OOP 解决此问题的最佳方法是什么?

java - 我该如何解决这个递归二叉树问题?

c# - 返回某些东西时完全停止递归