gpt4 book ai didi

python - 双向链表迭代器python

转载 作者:太空狗 更新时间:2023-10-30 01:02:30 25 4
gpt4 key购买 nike

我正在构建一个双向链表,我正在努力在 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一个遍历双向链表的例子。

这是一个简化的例子:

class Link:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next

def __iter__(self):
here = self
while here:
yield here.value
here = here.next

def __reversed__(self):
here = self
while here:
yield here.value
here = here.prev

if __name__ == '__main__':
a = Link('raymond')
b = Link('rachel', prev=a); a.next=b
c = Link('matthew', prev=b); b.next=c

print 'Forwards:'
for name in a:
print name
print
print 'Backwards:'
for name in reversed(c):
print name

关于python - 双向链表迭代器python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15710895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com