我有这个链表的实现,
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/