我正在构造一个双链表,我正在PYTHON中努力构造一个双链表迭代器方法。
到目前为止这是我的密码
class DoubleListNode:
def __init__(self,data):
self.data=data
self.prev = None
self.next= None
class ListIterator:
def __init__(self):
self._current = self.head
def __iter__(self):
return self
def next(self):
if self.size == 0 :
raise StopIteration
else:
item = self._current.data
self._current=self._current.next
return item
class DoublyLinkedList:
def __init__(self):
self.head= None
self.tail= None
self.size = 0
def add(self,data):
newnode= DoubleListNode(data)
self.size+=1
if self.head is None:
self.head = newnode
self.tail = self.head
elif data < self.head.data: # before head
newnode.next = self.head
self.head.prev= newnode
self.head= newnode
elif data > self.tail.data: # at the end
newnode.prev= self.tail
self.tail.next= newnode
self.tail=newnode
else:
curNode = self.head
while curNode is not None and curNode.data < data:
curNode=curNode.next
newnode.next= curNode
newnode.prev=curNode.prev
curNode.prev.next= newnode
curNode.prev=newnode
def remove(self,data):
curNode=self.head
while curNode is not None and curNode.data!= data:
curNode= curNode.next
if curNode is not None:
self.size -= 1
if curNode is self.head:
self.head= curNode.next
else:
curNode.prev.next=curNode.next
if curNode is self.tail:
self.tail=curNode.prev
else:
curNode.next.prev=curNode.prev
当我运行一个测试时,它说TypeError: iteration over non-sequence
。我做错什么了吗?
下面是双链表类的一个例子。
发布时,代码不会初始化(即未定义self.head)。
但总的来说,你走的是正确的道路。请看the source for Python's collections.OrderedDict以获得遍历双链表的计算示例。
下面是一个简单的例子:
我认为有两件重要的事情要解决。
首先,您的
DoublyLinkedList
类没有__iter__
方法。您可能希望创建一个返回ListIterator
实例的实例。也许您试图手动执行此操作,但这是正常的方法。其次,需要修复
ListIterator
中的代码才能正常工作。当前,__init__
方法无法正确初始化,并且next
方法尝试访问不存在的成员变量,如size
。下面是一个我认为可行的实现:
另外,在当前代码中,您定义的类没有基。这在Python 3中是可以的(默认情况下,
object
将是基础),但在Python 2中,这将导致获得一个“旧样式”类。旧样式的类已被弃用,您将发现某些语言功能无法正常使用它们(尽管据我所知,迭代中没有任何功能)。另一方面,如果已经在使用Python 3,则需要在迭代器类中定义一个__next__
方法,而不是next
(不带下划线)。相关问题 更多 >
编程相关推荐