DuIterator.py
# 迭代器模式 Iterator Pattern # Doubly Linked List class Node(object): def __init__(self, value, nextNode, prevNode): self.value = value self.next = nextNode self.prev = prevNode class DoublyLinkedList(object): def __init__(self): self.size = 0 self.head = None self.tail = None def isEmpty(self): return self.head is None def addLast(self, value): if self.isEmpty(): tmp = Node(value, None, None) self.head = tmp self.tail = tmp self.size += 1 return self.tail.next = Node(value, None, self.tail) self.tail = self.tail.next self.size += 1 def getIterator(self): return DLinkIterator(self.head) def getReverseIterator(self): return DLinkReverseIterator(self.tail) # Forward Iterator: class DLinkIterator(object): def __init__(self, startNode): self.current = startNode def hasNext(self): return self.current != None def next(self): if not self.hasNext(): raise IndexError val = self.current.value self.current = self.current.next return val # Reverse Iterator: class DLinkReverseIterator(object): def __init__(self, startNode): self.current = startNode def hasNext(self): return self.current != None def next(self): if not self.hasNext(): raise IndexError val = self.current.value self.current = self.current.prev return val
main.py 调用:
# 迭代器模式 Iterator Pattern myList = DuIterator.DoublyLinkedList() myList.addLast("Hello") myList.addLast("Geovin Du") myList.addLast("Goodbye") myList.addLast("涂聚文") # Iterate the list forwards: forwardIter = myList.getIterator() while forwardIter.hasNext(): print(forwardIter.next()) print("\n")
输出:
Hello Geovin Du Goodbye 涂聚文
标签:__,None,return,Iterator,Python,Pattern,self,current,def From: https://www.cnblogs.com/geovindu/p/16820099.html