我正在用Python实现一个链表。{linkedl1>实现几乎与实际类分开使用。我试着在一个班里做。在
我想加入的元素是3。我想这需要某种形式的递归。在这里,我添加两个元素(1.0和-1.0),然后打印列表。在
ll = LinkedList(1.0)
ll.insert_front(-1.0)
print(ll._linkedlist)
#output
[-1.0, [1.0, None]]
这看起来不错。注意,最后一个元素包含第二个元素(1.0)和指向None
-在这里显示为[1.0, None]
然而,每当我试图添加第三个元素时,这就崩溃了。在
^{pr2}$我想要的是以下输出:
[3.0, [-1.0, [1.0, None]]]
有什么办法吗?我目前的实现如下。在
class LinkedList(object):
"""A data structure implemented in Python.
"""
def __init__(self, head):
"""Initialize List."""
self.head = head
self.size = 1
self.next = None
self._linkedlist = [self.head, self.next]
empty_ll = None
def insert_front(self, element):
self.next = self.head
self.head = element
self.size += 1
self._linkedlist[0] = self.head
self._linkedlist[1] = [self.next, empty_ll]
#print out the head of the linked list
def __repr__(self):
return 'LinkedList(%s)' % (self.head)
目前没有回答
相关问题 更多 >
编程相关推荐