由于双链表有两个虚拟节点,一个是头,另一个是尾。我可以通过self.__current == None: raise StopIteration
跳过假尾节点,但我不知道如何通过假头节点并继续遍历下面的节点。
class LinkedListDLL:
def __init__(self):
self.__head = NodeDLL(None)
self.__head.set_next(self.__head)
self.__head.set_prev(self.__head)
self.__count = 0
def size(self):
return self.__count;
def is_empty(self):
return self.__count == 0
def add_before(self, item, curr):
new_node = NodeDLL(item)
new_node.set_next(curr)
new_node.set_prev(curr.get_prev())
curr.set_prev(new_node)
new_node.get_prev().set_next(new_node)
self.__count += 1
def add_to_head(self, item):
self.add_before(item, self.__head.get_next())
def add_to_tail(self, item):
self.add_before(item, self.__head)
def remove_from_head(self):
self.remove(self.__head.get_next())
def remove_from_tail(self):
self.remove(self.__head.get_prev())
def remove(self, curr):
curr.get_prev().set_next(curr.get_next())
curr.get_next().set_prev(curr.get_prev())
self.__count -= 1
def __iter__(self):
return LinkedListIterator(self.__head)
class LinkedListIterator:
def __init__(self, head):
self.__current = head
def __next__(self):
if self.__current == None :
raise StopIteration
else:
item = self.__current.set_data.get_next()
self.__current = self.__current.get_next()
return item
您应该重构代码,记住NodeDLL(None)
可能与None
不同。完成后:
def __next__(self):
if not self.__current.get_next():
raise StopIteration
#Skips first value in list, i.e. head
self.__current = self.__current.get_next()
return self.__current